我已经阅读了101个linq样本,他们似乎有一些我正在尝试做的事情但却无法把它放在一起。我有一个像这样的查询,它将我的'客户'加入一些'订单'值(例如所有订单的总数和订单数量)。
SELECT *
FROM cm_Customers
LEFT OUTER JOIN
(
SELECT UserID, SUM(Total) as Total, COUNT(OrderID) as Orders
FROM cm_orders
GROUP BY UserID
) TOTALS ON cm_Customers.UserID = TOTALS.UserID
ORDER BY TOTALS.Total DESC
我想出了如何进行左外连接但是我确实看到了任何方法来获得总和而不分组?我没有看到任何关于总和分组的例子,然后将这个结果连接回另一个选择。
var x =
from c in db.Customers
join o in db.Orders on c.UserID equals o.UserID into oo
from o in oo.DefaultIfEmpty()
select new { FirstName = c.FirstName, SUM??(o.Total), };
此时我似乎只是在转动轮子。任何帮助将不胜感激。
答案 0 :(得分:1)
您可以在加入后执行group by
。结果应完全相同:
var x = from c in db.Customers
join o in db.Orders on c.UserID equals o.UserID into oo
from o in oo.DefaultIfEmpty()
group new { c, o } by c.UserID into g
select new {
Customer = g.FirstOrDefault().c,
Total = g.Sum(x => x.o.Total)
Count = g.Select(x => x.o.OrderId).Distinct().Count()
};