Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the sum of multiple columns

I have three columns, which I am trying to get the sum of each one returned. I can do it for one column:

var data = db.Test.Sum(x => x.Column1);

I can't figure out how to get the sum for three columns though. I tried selecting the values into and summing them, but that didn't work.

var data = db.Test.Select(x=> new { x.Column1, x.Column3, x.Column3}).Sum();

I am after the result of each column separately, not a sum of all the columns.

like image 975
Joseph Avatar asked Aug 25 '14 15:08

Joseph


1 Answers

var sums = db.Tests
    .GroupBy(x => true)
    .Select(x => new 
    { 
        SumColumn1 = x.Sum(y => y.Column1), 
        SumColumn2 = x.Sum(y => y.Column2), 
        SumColumn3 = x.Sum(y => y.Column3) 
    });

The GroupBy(x => true) statement places all items into a single group. The Select statement the allows operations against each group. In this case the only group is a group of all items that allows us to return the Sum of each column.

like image 168
Rob Epstein Avatar answered Oct 14 '22 13:10

Rob Epstein