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

查看:36
本文介绍了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

这是没有 group by 的聚合.除了发出四个单独的查询(一个计数和三个总和)之外,我似乎找不到任何方法来做到这一点.有什么想法吗?

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?

推荐答案

这就是我发现的,好像你仍然需要做一个 group by...可以只使用常量:

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天全站免登陆