LINQ聚合在多个表中

时间:2010-06-09 18:08:28

标签: c# linq grouping

我想在LINQ to SQL中复制这个查询,但是对于如何操作却不太熟悉。

SELECT A.Recruiter, SUM(O.SaleAmount * I.Commission)  --This sum from fields in two different tables is what I don't know how to replicate
FROM Orders AS O
INNER JOIN Affiliate A ON O.AffiliateID = A.AffiliateID
INNER JOIN Items AS I ON O.ItemID = I.ItemID
GROUP BY A.Recruiter

我到目前为止:

from order in ctx.Orders
join item in ctx.Items on order.ItemI == item.ItemID
join affiliate in ctx.Affiliates on order.AffiliateID == affiliate.AffiliateID
group order  //can I only group one table here?
  by affiliate.Recruiter into mygroup
select new { Recruiter = mygroup.Key, Commission = mygroup.Sum(record => record.SaleAmount * ?????) };

2 个答案:

答案 0 :(得分:1)

group new {order, item} by affiliate.Recruiter into mygroup 
select new {
  Recruiter = mygroup.Key,
  Commission = mygroup
    .Sum(x => x.order.SaleAmount * x.item.Commission)
}; 

另一种编写查询的方法:

from aff in ctx.Affiliates
where aff.orders.Any(order => order.Items.Any())
select new {
  Recruiter = aff.Recruiter,
  Commission = (
    from order in aff.orders
    from item in order.Items
    select item.Commission * order.SaleAmount
    ).Sum()
};

答案 1 :(得分:1)

尝试linqpad,只需谷歌,这个神奇的工具!

相关问题