LINQ到SQL:怎么没有GROUP BY聚集?(Linq to SQL: how to aggre

2019-08-22 07:41发布

我寻找的LINQ到SQL相当于此查询:

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

这是一个没有一组通过的聚集体 。 我似乎无法找到任何方式做到这一点,短发卡四个单独的查询(一个计数和三个总和)。 有任何想法吗?

Answer 1:

这是我发现好像你还要做一组由...可以只使用常数:

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]


Answer 2:

您可以使用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) 
                      });


文章来源: Linq to SQL: how to aggregate without a group by?
标签: linq-to-sql