tags:

views:

103

answers:

2

I want to replicate this query in LINQ to SQL but am too unfamiliar with how to do it.

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

I've got this far:

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  A: 
group new {order, item} by affiliate.Recruiter into mygroup 
select new {
  Recruiter = mygroup.Key,
  Commission = mygroup
    .Sum(x => x.order.SaleAmount * x.item.Commission)
}; 

And an alternative way of writing the query:

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()
};
David B
awesome.. exactly the syntax I was missing....
Clyde
I'm curious about that last example -- Recruiter is not unique on the Affiliate table (these are secondary commissions going to the guy who recruited the affiliate, not the affiliate itself). Is that second one going to return a record for each unique Affiliate, not Recruiter?
Clyde
Yes, one record per Affiliate. Generally in queries of the form - from-join-join-groupby, the group by is a way to get back to the original record, but I guess that's not true in your case.
David B
+1  A: 

try linqpad, just Google, amazing tool!

System.ArgumentException