Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq-to-SQL statement for multiple aggregate values in single expression

Tags:

c#

linq-to-sql

How would I write a Linq-to-SQL statement for the following TSQL?

select 
  count(*),
  sum(Amount),
  avg(Amount),
  min(Amount),
  max(Amount) 
from 
  TableName
like image 314
Jeff Langston Avatar asked May 07 '10 15:05

Jeff Langston


1 Answers

HACK ALERT, but it works. Try to group your records by a condition all of them share:

var result = from g in db.Employees
        group g by g.Id.GetType() == typeof(int) into gg
        select new 
        {
            Count = gg.Count(),
            Sum = gg.Sum(x => x.Salary)
        };

This generates the SQL:

SELECT COUNT(*) AS [Count], SUM([t1].[Salary]) AS [Sum]
FROM (
SELECT 1 AS [value], [t0].[Salary]
FROM [dbo].[Employee] AS [t0]
) AS [t1]
GROUP BY [t1].[value]

There is a subquery involved, but hey! it's only one db trip

like image 62
alex.cedeno Avatar answered Nov 15 '22 12:11

alex.cedeno