在一个 LINQ 查询中获取两列的总和而不进行分组 [英] Get sum of two columns in one LINQ query without grouping
问题描述
我想在一个查询中总结一个表的三个不同字段.我想要一个相当于这个 T-SQL 的 linq:
I want to sum up three different fields of a table in one query. I want a linq equivalent of this T-SQL:
select sum(fld1), SUM(fld2), SUM(fld3) from MyTable where classID = 5
我发现的所有示例都使用 group by 或多次调用查询,每个需要汇总的字段一次.
All examples I have found either use a group by or call the query multiple times, once for each field that needs to be summed up.
我现在有这样的事情.但我不想在其中添加 group by 子句,因为它的 T-SQL 形式不需要它.
I have something like this now. But I don't want to add a group by clause to it as it is not required in its T-SQL form.
from a in MyTable
where a.classID == 5
group a by a.classID into g
select new
{
Sumfld1 = g.Sum(x => x.fld1 ),
Sumfld2 = g.Sum(x => x.fld2),
Sumfld3 = g.Sum(x => x.fld3)
}
有什么建议吗?感谢您抽出宝贵时间.
Any suggestions? Thanks for your time.
推荐答案
事实证明,在 linq-to-sql 中,您可以通过以下方式实现:
As it turns out, in linq-to-sql you can get very close by doing:
from a in MyTable
where a.classID == 5
group a by 0 into g
select new
{
Sumfld1 = g.Sum(x => x.fld1),
Sumfld2 = g.Sum(x => x.fld2),
Sumfld3 = g.Sum(x => x.fld3)
}
(注意0的分组)
它不会转换为 sql GROUP BY
,而是来自子查询的多个 SUM
的 SELECT
.就执行计划而言,它甚至可能是相同的.
It does not translate into a sql GROUP BY
, but a SELECT
of multiple SUM
s from a subquery. In terms of execution plan it may even be the same.
Entity Framework 仍然创建一个 GROUP BY
,尽管是通过 0
.
Entity Framework still creates a GROUP BY
, albeit by 0
.
这篇关于在一个 LINQ 查询中获取两列的总和而不进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!