Linq to SQL: how to aggregate without a group by?

后端 未结 2 1869
北海茫月
北海茫月 2020-12-05 13:09

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         


        
相关标签:
2条回答
  • 2020-12-05 13:32

    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)
        };
    

    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]
    
    0 讨论(0)
  • 2020-12-05 13:51

    You can do the same query using Lambda expression as follows:

      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 讨论(0)
提交回复
热议问题