Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sum of two columns in one LINQ query without grouping

I want to sum up three different fields of a table in one query. I want a linq equivalent of this T-SQL:

select sum(fld1), SUM(fld2),  SUM(fld3)   from MyTable where classID = 5

All examples I have found either use a group by or call the query multiple times, once for each field that needs to be summed up.

I have something like this now. But I don't want to add a group by clause to it as it is not required in its T-SQL form.

from a in MyTable
where a.classID == 5
group a by a.classID into g
select new 
{
Sumfld1 =  g.Sum(x => x.fld1 ), 
Sumfld2 = g.Sum(x => x.fld2),
Sumfld3 = g.Sum(x => x.fld3)
}

Any suggestions? Thanks for your time.

like image 497
user20358 Avatar asked Apr 20 '12 03:04

user20358


People also ask

How do you sum two columns in LINQ?

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

How do you find the sum of 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#.

What is the advantage of LINQ in C#?

Advantages of Using LINQLINQ offers a common syntax for querying any type of data sources. Secondly, it binds the gap between relational and object-oriented approachs. LINQ expedites development time by catching errors at compile time and includes IntelliSense & Debugging support. LINQ expressions are Strongly Typed.


1 Answers

As it turns out, in linq-to-sql you can get very close by doing:

from a in MyTable
where a.classID == 5
group a by 0 into g
select new 
{
    Sumfld1 = g.Sum(x => x.fld1), 
    Sumfld2 = g.Sum(x => x.fld2),
    Sumfld3 = g.Sum(x => x.fld3)
}

(note the group by 0)

It does not translate into a sql GROUP BY, but a SELECT of multiple SUMs from a subquery. In terms of execution plan it may even be the same.

Entity Framework still creates a GROUP BY, albeit by 0.

like image 145
Gert Arnold Avatar answered Nov 05 '22 14:11

Gert Arnold