我想使用linq计算每个季度每个产品的金额总和。在SQL中我会使用:
我怎么能在linq中做到这一点? 我试过这段代码:
public List<ValuePairPlanned> GetQuantityOfEachProductPlannedForRelease(int departmentId)
{
var amountByProducts = (from rp in _context.ReleasePlans
join p in _context.Products
on rp.ProductProductId equals p.ProductId
where rp.DepartmentDepartmentId == departmentId
group new { rp, p } by new { rp.ProductProductId, p.ProductId, p.ProductName, rp.DateTime, rp.Amount }
into grp
select new
{
grp.Key.ProductName,
grp.Key.DateTime,
PlannedAmount = grp.Sum(g => g.rp.Amount)
}).Distinct().ToList().ConvertAll(x => new ValuePairPlanned()
{ PlannedAmount = x.PlannedAmount, Quarter = (x.DateTime.AddDays(2).Month - 1) / 3 + 1, ProductName = x.ProductName });
return amountByProducts;
}
但结果我得到每个季度每件产品的金额。我该如何解决?谢谢你的帮助。
答案 0 :(得分:0)
由于您使用的是Entity Framework,请查看DbFunctions,以便您可以在SQL Server上添加日期。如果您不使用DbFunctions
,则必须先通过ToList()
获取已连接的表格,然后执行数据计算以计算季度。
以下内容应该让你非常接近:
var amountByProducts = from p in _context.Products
join rp in _context.ReleasePlans
on p.ProductId equals rp.ProductId
where rp.DepartmentDepartmentId == departmentId
group new
{
p.ProductName,
Quarter = (DbFunctions.AddDays(rp.DateTime,2).Month - 1) / 3 + 1,
rp.Amount
}
// group all product plans in a given quarter
by new
{
p.ProductName, // shouldn't this be ProductId?
Quarter = (DbFunctions.AddDays(rp.DateTime,2).Month - 1) / 3 + 1
}
into grp
// from the grouped entries, sum the amounts
select new ValuePairPlanned()
{
PlannedAmount = grp.Sum(g => g.Amount),
Quarter = grp.Key.Quarter,
ProductName = grp.Key.ProductName
};
return amountByProducts.ToList();