C# LINQ:使用 INNER JOIN、Group 和 SUM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/530925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:00:37  来源:igfitidea点击:

LINQ: Using INNER JOIN, Group and SUM

c#linq.net-3.5

提问by Nic

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.

我正在尝试使用 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

What I have been trying is the following LINQ code

我一直在尝试的是以下 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)};

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

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

采纳答案by Nick Berardi

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

回答by Tun

For me (using 4.0), the following works.

对我来说(使用 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) 
            };

回答by Muhammad Awais

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