I need to join two tables (Movimientos and Cuentas), group by CuentasId and make a SUM of Movimientos.Monto
Movimientos has a CuentasId to join this, and I can get the data from Cuentas but can not get the Sum.
This is my best approach, any help will be preciated, I'm a little confused with the syntax. Thanks in advance and kind regards,
var cuentas = (from mov in _data.Movimientos
join ct in _data.Cuentas
on mov.CuentasId equals ct.CuentasId
where ct.IsDeleted == 0 && mov.IsDeleted == 0
group ct by new
{
CuentasId = ct.CuentasId,
Alias = ct.Alias,
Moneda = ct.Monedas.Nombre,
Signo = ct.Monedas.Signo,
Banco = ct.Bancos.Nombre
} into ctg
select new
{
Alias = ctg.Key.Alias,
Moneda = ctg.Key.Moneda,
Signo = ctg.Key.Signo,
Banco = ctg.Key.Banco,
Monto = ctg.Sum(mov.Monto)
}
).ToList();
You need to group the value you want to sum like this
group mov.Monto by new { ..... } into ctg
Then ctg will be a collection of mov.Monto values grouped by your list of properties of ct and you'd just call Sum on ctg in your select
Monto = ctg.Sum()
So your new query would be
var cuentas = (from mov in _data.Movimientos
join ct in _data.Cuentas
on mov.CuentasId equals ct.CuentasId
where ct.IsDeleted == 0 && mov.IsDeleted == 0
group mov.Monto by new
{
CuentasId = ct.CuentasId,
Alias = ct.Alias,
Moneda = ct.Monedas.Nombre,
Signo = ct.Monedas.Signo,
Banco = ct.Bancos.Nombre
} into ctg
select new
{
Alias = ctg.Key.Alias,
Moneda = ctg.Key.Moneda,
Signo = ctg.Key.Signo,
Banco = ctg.Key.Banco,
Monto = ctg.Sum()
}).ToList();
You could also try grouping by first and then just summing the items later:
var cuentas = (from mov in _data.Movimientos.Where(w => w.IsDeleted == 0).GroupBy(g => g.CuentasId)
join ct in _data.Cuentas.Where(w => w.IsDeleted == 0).GroupBy(g => new { CuentasId = g.CuentasId, Alias = g.Alias, Monedas = g.Monedas.Nombre, Signo = g.Monedas.Signo, Banco = g.Bancos.Nombre })
on mov.Key.CuentasId equals ct.Key.CuentasId
select new
{
Alias = ct.Key.Alias,
Moneda = ct.Key.Moneda,
Signo = ct.Key.Signo,
Banco = ct.Key.Banco,
Monto = mov.Sum(s => s.Monto)
}
).ToList();
Related
I'm struggling with what is a rather simple SQL select statement. How can this be translated into LINQ?
select
o.IdOrder, Date, s.suma, name, adresa
from
Clients c
join
Orders o on (c.IdClient = o.IdClient)
join
(select IdOrder, sum(price) suma
from OrderProduct
group by IdOrder) s on (o.IdOrder = s.IdOrder);
If you could point me in the right direction, I would greatly appreciate it.
This is what I have so far:
var y = from w in db.OrderProducts
group w by w.IdOrder into TotaledOrder
select new
{
IdOrder = TotaledOrder.Key,
price = TotaledOrder.Sum(s => s.price)
};
var i = 0;
var cc = new dynamic[100];
foreach (var item in y)
{
cc[i++] = db.Orders.Where(t => t.IdOrder == item.IdOrder)
.Select(p => new
{
IdOrder = item.IdOrder,
price = item.price,
}).Single();
}
Your SQL doesn't really give an idea on your underlying structure. By a guess on column names:
var result = from o in db.Orders
select new {
IDOrder = o.IDOrder,
Date = o.Date,
Suma = o.OrderProduct.Sum( op => op.Price),
Name = o.Client.Name,
Adresa = o.Client.Adresa
};
(I have no idea what you meant by the loop in your code.)
I have a 3 tables joined in the statement below:
var data = from x in dbContext.Base_Agencies
from u in dbContext.Base_AgencyInstances
from o in dbContext.Payment2Account_SecurityRuleAgencies
where u.AgencyId == x.AgencyId
where o.AgencyId == x.AgencyId
where u.AgencyInstanceId == param.AgencyInstanceId
select new RsSecurityParamsResult
{
AgencyId = x.AgencyId,
AgencyNameView = u.AgencyNameView,
Stamp = u.Stamp,
Pni = x.Pni,
Prefix = u.Prefix,
ServiceEnabled = o.ServiceEnabled,
DisabledDateTime = o.DisabledDateTime,
AmountHourTresholdWarning = o.AmountHourTresholdWarning,
AmountHourTresholdStop = o.AmountHourTresholdStop,
CountHourTresholdWarning = o.CountHourTresholdWarning,
CountHourTresholdStop = o.CountHourTresholdStop
};
The problem is that in some examples there won't be a row for agency in table 'o'. In this situation I would like to select values only from other tables, except 'o' table. How should I do that?
I think you might want to do a LEFT OUTER JOIN like
var data = from x in dbContext.Base_Agencies
join u in dbContext.Base_AgencyInstances
on u.AgencyId == x.AgencyId
join o in dbContext.Payment2Account_SecurityRuleAgencies
on o.AgencyId == x.AgencyId into lrs
from lr in lrs.DefaultIfEmpty()
select new RsSecurityParamsResult
{
AgencyId = x.AgencyId,
AgencyNameView = u.AgencyNameView,
Stamp = u.Stamp,
Pni = x.Pni,
Prefix = u.Prefix,
ServiceEnabled = lr.ServiceEnabled ?? "Default",
...... // other code similar ........
};
Correct solution is:
var data = from x in dbContext.Base_Agencies
join u in dbContext.Base_AgencyInstances
on x.AgencyId equals u.AgencyId
join o in dbContext.Payment2Account_SecurityRuleAgencies
on x.AgencyId equals o.AgencyId into lrs
from lr in lrs.DefaultIfEmpty()
where u.AgencyInstanceId == param.AgencyInstanceId
select new RsSecurityParamsResult
{
AgencyId = x.AgencyId,
AgencyNameView = u.AgencyNameView,
Stamp = u.Stamp,
Pni = x.Pni,
Prefix = u.Prefix,
ServiceEnabled = lr.ServiceEnabled,
DisabledDateTime = lr.DisabledDateTime,
AmountHourTresholdWarning = lr.AmountHourTresholdWarning ,
AmountHourTresholdStop = lr.AmountHourTresholdStop,
CountHourTresholdWarning = lr.CountHourTresholdWarning ,
CountHourTresholdStop = lr.CountHourTresholdStop
};
So i'm using Quartz to create a task scheduler for my program and I'm having issues where if there are multiple jobs to run, it will repeatedly execute the query for the respective job but then never exectues the very next line. It's as if it hangs as soon as i hit tolist(). Any ideas?
try
{
//work on query further , need to get client ID correctly
if (vehicleses.Count == 0)
return null;
string siteId = QueryExportSiteWithId(exportSiteId).SiteId;
string clientId = vehicleses[0].ClientID;
db.Database.Log = Console.Write;
var inventoryyReturn = from i in db.Inventory_Vehicles
where dealerIdList.Any(c => c == i.ClientID) && i.Archived != "1" && i.Holding != "1" &&
i.Status == "A"
select i;
var inventoryDescription = from i in db.Inventory_Descriptions
where
inventoryyReturn.Any(
c => new {client = c.ClientID, inv = c.ID} == new {client = i.ClientID, inv = i.InventoryID})
select i;
var settingsExports = from i in db.Settings_Exports
where inventoryyReturn.Any(c => c.ClientID == i.ClientID)
select i;
var settingLots = from i in db.Settings_Lots
where
inventoryyReturn.Any(
c => new {client = c.ClientID, lot = c.LotID} == new {client = i.ClientID, lot = i.ID})
select i;
var inventoryFeatures = from i in db.Inventory_Features
where
inventoryyReturn.Any(
c => new {client = c.ClientID, inv = c.ID} == new {client = i.ClientID, inv = i.InventoryID})
select i;
var inventoryPhotos = from i in db.Inventory_Photos
where
inventoryyReturn.Any(c => c.ID == i.InventoryID)
select i;
var longReturnListt = (from i in inventoryyReturn
join l in inventoryDescription on new {inv = i.ID, cli = i.ClientID} equals
new {inv = l.InventoryID, cli = l.ClientID} into descGroup
from m in descGroup.DefaultIfEmpty()
join s in settingsExports on i.ClientID equals s.ClientID into settingGroup
from sg in settingGroup.DefaultIfEmpty()
join sl in settingLots on new {client = sg.ClientID, lot = sg.LotID} equals
new {client = sl.ClientID, lot = sl.ID} into lotsGroup
from lg in lotsGroup.DefaultIfEmpty()
join se in db.Settings_ExportSites on new {client = lg.ClientID, lotId = i.LotID, site = siteId}
equals new {client = se.ClientID, lotId = se.LotID, site = se.Site} into exportGroup
from eg in exportGroup.DefaultIfEmpty()
join f in inventoryFeatures on new {inv = i.ID, cli = i.ClientID} equals
new {inv = f.InventoryID, cli = f.ClientID} into invFeatGroup
from ifg in invFeatGroup.DefaultIfEmpty()
join p in inventoryPhotos on i.ID equals p.InventoryID into photo
from photos in photo.DefaultIfEmpty()
orderby i.ID
select new {i, m, sg, photoo = photo.ToList(), lg, ifg, eg}
into grouped
group grouped by new {grouped.i.ClientID}
into groupedDone
//select groupedDone
from categories in groupedDone
select new NewType
{
InventoryVehicles = categories.i,
InventoryDescriptions = categories.m,
SettingsExports = categories.sg,
InventoryPhotos = categories.photoo,
SettingsLots = categories.lg,
InventoryFeatures = categories.ifg,
SettingsExportSites = categories.eg
}
).ToList();
// var sql = ((System.Data.Entity.Core.Objects.ObjectQuery) longReturnListt as ObjectQuery);
// var trace = sql.ToTraceString();
if (longReturnListt != null)
{
//returnList.AddRange(longReturnListt.);
return returnList;
}
return null;
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
I have two lists as follows:
var SeparatedEmployees = (from s in DataContext.HRM_EMP_TRMN.AsEnumerable()
where s.TRMN_FINL_STUS == "SA" && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on s.EMP_CODE equals e.EMP_CODE
where e.ACTIVE_STATUS == "A"
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
var ConfirmedEmployees = (from c in DataContext.HRM_EMP_FINL_STMT_MST.AsEnumerable()
where ((Convert.ToDateTime(c.FINL_STMT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(c.FINL_STMT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on c.EMP_CODE equals e.EMP_CODE
join s in DataContext.HRM_EMP_TRMN on c.EMP_CODE equals s.EMP_CODE
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
Tyring to remove the items from the first list, which are also in second list.
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ConfirmedEmployees.Contains(item)
select item).ToList();
Tried this one too:
FinalSeparatedEmployees = SeparatedEmployees.Except(ConfirmedEmployees).ToList<HRM_EMP_FINL_STMT_MSTModel>();
But not getting the accurate result. What I'm missing? Thanks.
Its better to use EMP_CODE because your objects are not comparable.
var ids = ConfirmedEmployees.Select(x => x.EMP_CODE).ToList();
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ids.Contains(item.EMP_CODE)
select item).ToList();
hi first time im asking here so il try to do it correctly
i have a problem im making a shopping basket and im nearly there but always a but
what i want to have is something like this
List<HKurv> KurvInnhold = (List<HKurv>)Session["KurvInnhold"];
DataClasses1DataContext db = new DataClasses1DataContext();
if (Session["KurvInnhold"] != null)
{
var query = from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
from d in KurvInnhold
where
d.VareKjøpt.Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
BestiltAntall = d.AntallValgt,
Price = b.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query;
Handlekurv1.DataBind();
}
But it does not allow for usage of db and list<> in same query
Solved! Modified magnus's answer
var kjopKollonne = from p in KurvInnhold
select p.VareKjøpt;
var query1 = (from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
where
kjopKollonne.Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
ArtNum = e.ArtNum,
Price = b.Price,
ModelName = a.ModelName,
}).ToList();
var query2 = from a in query1
join b in KurvInnhold on a.ArtNum equals b.VareKjøpt
select new
{
BestiltAntall = b.AntallValgt,
Price = a.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query2;
Handlekurv1.DataBind();
Try this:
var query1 = from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
from d in KurvInnhold
where
KurvInnhold.Select(k => k.VareKjøpt).Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
ArtNum = e.ArtNum,
Price = b.Price,
ModelName = a.ModelName,
}.ToList();
var query2 =
from a in query1
join b in KurvInnhold on a.ArtNum equals b.VareKjøpt
select new
{
BestiltAntall = b.AntallValgt,
Price = a.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query2;
Handlekurv1.DataBind();