Linq to SQL:如何在没有分组依据的情况下进行汇总? [英] Linq to SQL: how to aggregate without a group by?

查看:78
本文介绍了Linq to SQL:如何在没有分组依据的情况下进行汇总?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搜索与此查询等效的Linq-to-SQL:

I am searching for the Linq-to-SQL equivalent to this query:

SELECT
  [cnt]=COUNT(*),
  [colB]=SUM(colB),
  [colC]=SUM(colC),
  [colD]=SUM(colD)
FROM myTable

这是没有分组依据的汇总.除了发出四个单独的查询(一个Count和三个Sum)之外,我似乎找不到任何方法.有什么想法吗?

This is an aggregate without a group by. I can't seem to find any way to do this, short of issuing four separate queries (one Count and three Sum). Any ideas?

推荐答案

这是我发现您似乎仍然需要按...进行分组的方法,只需使用常量即可.

This is what I found seems like you still have to do a group by...can just use constant:

var orderTotals =
    from ord in dc.Orders
    group ord by 1 into og
    select new
    {
        prop1 = og.Sum(item=> item.Col1),
        prop2 = og.Sum(item => item.Col2),
        prop3 = og.Count(item => item.Col3)
    };

这将产生以下SQL,虽然它不是最佳的,但是可以工作:

This produces the following SQL, which is not optimal, but works:

SELECT SUM([Col1]) as [prop1], SUM([Col2]) as [prop2], COUNT(*) AS [prop3]
FROM (
    SELECT 1 AS [value], [t0].[Col1], [t0].[Col2], [t0].[Col3]
    FROM [table] AS [t0]
    ) AS [t1]
GROUP BY [t1].[value]

这篇关于Linq to SQL:如何在没有分组依据的情况下进行汇总?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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