简体   繁体   English

使用SUM()将SQL语句转换为Linq / Entity Framework

[英]Converting SQL statement using SUM() to Linq/Entity Framework

I'm trying to figure out how to convert the following SQL statement to Entity Framework using Linq: 我试图弄清楚如何使用Linq将以下SQL语句转换为Entity Framework:

SELECT SUM(Column1) AS Correct
     , SUM(Column2) AS Incorrect
     , UserName
FROM   Stats 
WHERE (StatType = 0)
GROUP BY UserName
ORDER BY UserName 

For the purposes of this question, all the column types in the DB are type INT, and there are multiple rows of data per user. 出于此问题的目的,数据库中的所有列类型均为INT类型,并且每个用户有多行数据。 I basically want 3 columns in my output, with the total of correct & incorrect selections for each user. 我基本上希望输出中有3列,每个用户的正确和不正确选择的总数。

It seems like such a simple SQL statement but whatever I try in something like LinqPad, I always get errors. 看起来像是一条简单的SQL语句,但是无论我在LinqPad之类的程序中尝试什么,我总是会出错。 I must be missing something relatively simple. 我一定缺少一些相对简单的东西。 As soon as I start add a ".Sum" clause I get compilation errors etc. 一旦我开始添加“ .Sum”子句,我就会收到编译错误等信息。

Stats.Where(s => s.StatType == 0)
     .GroupBy(s => s.UserName)
     .Select(x => new {  Correct = x.Column1
                       , Incorrect = x.Column2
                       , User=x.UserName})
     .ToList()

The following should do the trick: 以下应该可以解决问题:

Stats.Where(s => s.StatType == 0)
     .GroupBy(s => s.UserName)
     .Select(x => new { Correct = x.Sum(y => y.Column1),
                        Incorrect = x.Sum(y => y.Column2),
                        User = x.Key})
     .ToList();

Please note that GroupBy returns an IEnumerable<IGrouping<TKey, TValues>> . 请注意, GroupBy返回IEnumerable<IGrouping<TKey, TValues>>
That means that the x inside the Select is an IGrouping<TKey, TValues> . 这意味着Select内的xIGrouping<TKey, TValues> That in turn is basically just an IEnumerable<T> that contains all rows of that group along with the key of this group. 基本上,这只是一个IEnumerable<T> ,它包含该组的所有行以及该组的键。
So, to get the sum of all items in a group, you need to use Sum on the grouping and specify which columns to sum as a parameter to the Sum method. 因此,要获取组中所有项目的总和,您需要在分组中使用Sum并指定要累加哪些列作为Sum方法的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM