Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 

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?

like image 443
Portman Avatar asked Oct 20 '09 20:10

Portman


People also ask

Can we use aggregate function without GROUP BY?

While all aggregate functions could be used without the GROUP BY clause, the whole point is to use the GROUP BY clause. That clause serves as the place where you'll define the condition on how to create a group. When the group is created, you'll calculate aggregated values.

How do you sum in LINQ?

In LINQ, you can find the sum of the given numeric elements by using the Sum() method. This method calculates the sum of the numeric value present in the given sequence. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.

How do you sum two columns in LINQ?

Items select new { Sum(p. Total), Sum(p. Done)};


1 Answers

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] 
like image 98
CSharpAtl Avatar answered Sep 25 '22 11:09

CSharpAtl