Linq to SQL:如何在没有 group by 的情况下进行聚合?

问题描述 投票:0回答:3

我正在寻找与此查询等效的 Linq-to-SQL:

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

这是没有分组依据的聚合。我似乎找不到任何方法来做到这一点,除了发出四个单独的查询(一个计数和三个求和)。有什么想法吗?

linq-to-sql
3个回答
50
投票

这就是我发现的,似乎你仍然需要进行分组...可以只使用常量:

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,这不是最优的,但可以工作:

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]

25
投票

您可以使用 Lambda 表达式执行相同的查询,如下所示:

  var orderTotals = db.Orders
                      .GroupBy( i => 1)
                      .Select( g => new
                      {
                           cnt = g.Count(), 
                           ScolB = g.Sum(item => item.ColB), 
                           ScolC = g.Sum(item => item.ColC) 
                      });

0
投票

另外,请参阅此处:https://github.com/dotnet/efcore/issues/27117

如果项目不存在(计数=0),我需要一个计数,但仅添加“group ~ by 1”就像内部联接并排除这些项目。
添加 .DefaultWhenEmpty()] 包括零计数

from orderType in dc.OrderTypes
from aggregate in (
    from ord in (
        from ord indc.Orders
        where ord.OrderType = orderType.OrderType
    ).DefaultIfEmpty()
    group ord by 1 into og
    select new {
        SumCol1 = og.Sum(item => item.Col1),
        SumCol2 = og.Sum(item => item.Col2),
        Count = og.Count(item => item != null)
        CountBool3 = og.Count(item => item != null && item.Bool3)
    }
    )
select new {
    orderType.OrderType,
    aggregate.SumCol1,
    aggregate.SumCol2,
    aggregate.Count,
    aggregate.CountBool3,
}        
© www.soinside.com 2019 - 2024. All rights reserved.