28

I am trying to perform the following SQL using LINQ and the closest I got was doing cross joins and sum calculations. I know there has to be a better way to write it so I am turning to the stack team for help.

SELECT T1.Column1, T1.Column2, SUM(T3.Column1) AS Amount
FROM T1
     INNER JOIN T2
        ON T1.T1ID = T2.T1ID
     INNER JOIN T3
        ON T2.T3ID = T3.T3ID
GROUP BY T1.Column1, T1.Column2

What I have been trying is the following LINQ code

var qTotal = from T2 in context.T2
             from T3 in context.T3
             where T3.T3ID == T3.T3ID
             group T3 by T2.T1ID into gT2T3
                  from T1 in context.T1
                  where gT2T3.Key.Equals(T1.T1ID)
                  select new { T1.Column1,T1.Column2,Amount = gT2T3.Sum(t => t.Column1)};

I know there has to be a better way to write it, I just do not know how, any help would be great!

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Nic
  • 732
  • 3
  • 11
  • 24

3 Answers3

38

Try this:

var total = from T1 in context.T1
            join T2 in context.T2 on T1.T2ID equals T2.T2ID
            join T3 in context.T3 on T2.T3ID equals T3.T3ID
            group T3 by new { T1.Column1, T1.Column2 } into g
            select new { 
                Column1 = T1.Column1, 
                Column2 = T2.Column2, 
                Amount = g.Sum(t3 => t3.Column1) 
            };
Nick Berardi
  • 54,393
  • 15
  • 113
  • 135
  • 1
    Thank you Nick, I initial thought the answer was incorrect but after rereading it and performing it again I realized I had a mistake in my initial attempt and your answer was spot on. thank you! – Nic Feb 10 '09 at 04:10
  • 5
    For newer .NET versions (4.0 and onwards?), have a look at twnaing's answer below. – Oskar Lundgren Nov 19 '14 at 15:55
24

For me (using 4.0), the following works.

var total = from T1 in context.T1
            join T2 in context.T2 on T1.T2ID equals T2.T2ID
            join T3 in context.T3 on T2.T3ID equals T3.T3ID
            group T3 by new { T1.Column1, T1.Column2 } into g
            select new { 
                Column1 = g.Key.Column1, 
                Column2 = g.Key.Column2, 
                Amount = g.Sum(t3 => t3.Column1) 
            };
Tun
  • 1,345
  • 13
  • 34
0

Below code is working for me :

                          var credit = (from bm in BulkMessage
                          join sms in SMS on bm.BulkMessageId equals sms.BulkMessageId
                          where bm.ProfileId == pid && bm.IsActive == true
                           group sms by sms.SMSCredit into g

                          select new { SMSCredits = g.Sum(s => s.SMSCredit) }).FirstOrDefault();
Muhammad Awais
  • 4,238
  • 1
  • 42
  • 37