LINQ:使用INNER JOIN,Group和SUM

时间:2009-02-10 02:50:03

标签: c# linq .net-3.5

我正在尝试使用LINQ执行以下SQL,而我最接近的是进行交叉连接和求和计算。我知道必须有更好的方法来编写它,所以我转向堆栈团队寻求帮助。

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

我一直在尝试的是以下LINQ代码

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

我知道必须有更好的方式来编写它,我只是不知道如何,任何帮助都会很棒!

3 个答案:

答案 0 :(得分:31)

试试这个:

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

答案 1 :(得分:19)

对我来说(使用4.0),以下工作。

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

答案 2 :(得分:0)

下面的代码对我有用:

                          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();