将MSSQL查询转换为Lambda表达式或LINQ。分组求和和排序

时间:2017-01-10 06:18:29

标签: c# sql linq lambda sum

我有一个SQL查询,用列值的总和提取排序数据。我有一个名为CustomerPoint的表,它有2列名为CusTomerIDPoint,我想提取点数最高SUM的人。这是我的SQL查询,它运行正常。但我需要使用LambdaExpressionsLinq查询在EF6.3中执行它。

SELECT SUM(Point) AS POINTS, CustomerID FROM CustomerPoint AS POINTS GROUP BY CustomerID ORDER BY POINTS

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

这样的事情:

from p in context.Points
group p by p.CustomerID into gr
select new { CustomerID = gr.Key, POINTS = gr.Sum(c=>c.Point) } into re
orderby re.POINTS

答案 1 :(得分:1)

请试一试。

from cp in db.CustomerPoints
Group cp by cp.CusTomerID into cpg
select new { CusTomerID = cpg.Key, Points = cpg.Sum(c => c.Point)}
orderby cpg.Points

答案 2 :(得分:1)

lambda形式的多样性:

var query = youContext.CustomerPoints
            .GroupBy(x => x.CustomerID)
            .Select(x => new { Points = x.Sum(y => y.Point),
                               CustomerID = x.Key })
            .OrderBy(x => x.Points);