0

查看下面的代码,我想按客户 ID 汇总/分组查询结果,其中客户 ID 列旁边的销售和收据列的总和。

var sales = from s in context.Sales
            select new { id = s.CustomerID, sales = s.Amount, receipts = (decimal)0 };

var receipts = from r in context.Receipts
            select new { id = r.CustomerID, sales = (decimal)0, receipts = r.Amount };

var summary = sales.Union(receipts).ToList();

我尝试使用以下组合来实现相同的目的:

var summary = sales.Union(receipts).GroupBy(e=>e.id).Select( ... )

……但无济于事。

期待获得正确的相关语法。

4

2 回答 2

0

试试这个

    var salesAndreceipts = from data in context.Receipts
                               join data2 in context.Receipts on data.CustomerID on data2.CustomerID
                               select new { id = r.CustomerID, sales = data.Sales, receipts = data2.Amount };

更新 从销售和收据中获取数据后,请尝试以下操作:

      var salesAndReceipts = sales.Union(receipts).ToList(); 


        var groupedData = from data in salesAndreceipts
                          group data by new {id=data.CustomerID}
                              into SalesRecepientGroup
                              Select new
                              {
                                  id = SalesRecepientGroup.Key.CustomerID,
                                  sales = SalesRecepientGroup.Sum(x=>x.Sales),
                                  receipts = SalesRecepientGroup.Sum(x=>x.Amount)

                              };

希望这可以帮助.. :)

更新

然后,您可以检查它在 EFProfiler 下生成的查询并优化这些查询。

于 2012-11-18T17:33:29.683 回答
0

你很接近,尽管我们必须猜测Select( ... )里面有什么。你可以这样做:

summary
    .GroupBy(s => s.id)
    .Select(g => new { id = g.Key,
                       salesSum = g.Sum(x => x.sales), 
                       receiptsSum = g.Sum(x => x.receipts)
                     })
于 2012-11-18T23:19:51.313 回答