2010-06-09 96 views
1

我想在LINQ to SQL中复制这个查询,但我不太熟悉如何去做。跨多个表的LINQ聚合

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 * ?????) }; 

回答

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() 
}; 
+0

真棒..正是我错过的语法.... – Clyde 2010-06-09 18:15:01

+0

我很好奇最后一个例子 - 招聘人员并不是唯一的联盟表(这些是辅助佣金去招聘联盟的人,而不是会员本身)。第二个人是否会为每个独特的加盟者而不是Recruiter返回记录? – Clyde 2010-06-09 18:27:17

+0

是的,每个会员一个记录。通常在查询表单 - 从 - 连接 - 连接 - groupby中,group by是回到原始记录的一种方式,但我想你的情况并非如此。 – 2010-06-09 18:30:27

1

试linqpad,只是谷歌,令人惊讶的工具!