2010-06-09 108 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,只是谷歌,令人驚訝的工具!