在一个LINQ查询中获取两列的总和,而不进行分组 [英] Get sum of two columns in one LINQ query without grouping

查看:344
本文介绍了在一个LINQ查询中获取两列的总和,而不进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个查询中总结一个表的三个不同字段。我想要一个等价于这个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

我发现所有示例都使用一个组或调用查询多个次,每场需要总结一次。

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中,你可以非常接近: / p>

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 SUMs from a subquery. In terms of execution plan it may even be the same.

实体框架仍然创建一个 GROUP BY ,尽管 0

Entity Framework still creates a GROUP BY, albeit by 0.

这篇关于在一个LINQ查询中获取两列的总和,而不进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆