Linq与两个表中的sum和group

时间:2017-06-09 12:30:48

标签: c# linq group-by sum

嗨,我有两张桌子,

产品:

ProductID | IssueDate | Amount

1           2017-06-01  1000
2           2017-06-01  1000
3           2017-06-02  500

和信用:

ProductID | Amount

1           500
1           500
2           1000
3           500

如果我在SQL Server中使用这样的查询:

SELECT p.IssueDate, SUM(p.Amount), SUM(p.Total) 
FROM (SELECT p.IssueDate, SUM(p.Amount) AS Amount, 
(SELECT TOP 1 SUM(c.Amount) FROM Credit c WHERE p.Id = c.ProductId) AS Total from Product p
GROUP BY p.IssueDate, p.Id) p
GROUP BY p.IssueDate

我得到了这个结果:

IssueDate | Amount | Total

2017-06-01  2000     2000
2017-06-02  500      500

在C#Linq中,我可以通过以下两个查询获取此数据:

var data = from p in Products.Collection
           select new
           {
              Product = p,
              Credits = Credit.Collection.Where(c => c.ProductID == p.ID).Sum(c => c.Amount)
           };

var result = from d in data
           group d by new
           {
               IssueDate = d.Product.IssueDate
           } into gr
           select new
           {
               IssueDate = gr.Key.IssueDate,
               Credits = gr.Sum(s => s.Credits),
               Total = gr.Sum(s => s.Product.Amount)
           };

var test = result.ToList();

有没有人知道更好(更简单)的解决方案来获得这个结果?也许在一个查询中?

1 个答案:

答案 0 :(得分:1)

How about:

Products.Collection.GroupBy(x => x.IssueDate)
            .Select(x => new
            {
                IssueDate = x.Key,
                Amount = x.Sum(p => p.Amount),
                Total = Credit.Collection.Where(c => x.Any(p => p.ProductID == c.ProductID)).Sum(c => c.Amount)
            }).ToList();