views:

184

answers:

1

Hey all. I'm not sure how I could express the following query in C# using Linq to SQL. Here is a short snippet of the pure SQL:

select t1.WholesalerID, t1.RetailerID,
    sum(t1.Col1) as 'Column 1',
    sum(t2.Col1) as 'Other Column 1',
    (sum(t1.Col1) - sum(t2.Col1)) as 'Column 1 Difference',
    sum(t1.Col2) as 'Column 2',
    sum(t2.Col2) as 'Other Column 2',
    (sum(t1.Col2) - sum(t2.Col2)) as 'Column 2 Difference'
    from Table1 t1
    inner join Table2 t2 on t1.WholesalerID = t2.WholesalerID
group by t1.WholesalerID, t1.RetailerID

Now, I've done Linq to SQL joins and group by's before, but I'm sure how to go about doing these together. I run into the problem when I'm attempting to sum the values from the joined tables. Thanks.

A: 

I've reached this solution: (didn't tested it though)

        var qry = from t in
                      (from t1 in Table1
                       join t2 in Table2 on t1.WholesalerID equals t2.WholesalerID
                       select new { t1, t2 })
                  group t by new { t.t1.WholesalerID, t.t1.RetailerID } into g
                  select new MyTypeWithDifferenceProp
                  {
                      WholesalerID = g.Key.WholesalerID,
                      RetailerID = g.Key.RetailerID,
                      Column1 = g.Sum(e => e.t1.Col1),
                      OtherColumn1 = g.Sum(e => e.t2.Col1),
                      Column2 = g.Sum(e => e.t1.Col2),
                      OtherColumn2 = g.Sum(e => e.t2.Col2),
                  };

This MyTypeWithDifferenceProp would have the Column1Difference and Column2Difference already defined.

bruno conde
Hey thanks a lot Bruno. The code worked great!