Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL equivalent of SUM GROUP BY SQL statement

I'm having a hard time figuring out how to translate this simple SQL statement to (c#) linq to SQL :

SELECT  table1.vat, SUM(table1.QTY * table2.FLG01 + table1.QTY * table2.FLG04) 
FROM table1
inner join table2 on table2.key= table1.key
where  '2010-02-01' <= table1.trndate   and  table1.trndate <= '2010-02-28'
Group by table1.vat

Any help is appreciated

like image 375
Savvas Sopiadis Avatar asked Jan 23 '23 14:01

Savvas Sopiadis


2 Answers

I'm still learning LINQ but this seems to work

var result = from t1 in table1
             from t2 in table2
             where t1.key == t2.key && DateTime.Parse("2010-02-01") <= t1.trndate && t1.trndate <= DateTime.Parse("2010-02-28")
             group new {t1,t2} by t1.vat into g
             select new { vat = g.Key, sum = g.Sum(p => p.t1.QTY*p.t2.FLG01 + p.t1.QTY*p.t2.FLG04)};

I hope in translates well to LINQ to SQL because I only tried it on objects.

like image 161
Jonas Elfström Avatar answered Feb 01 '23 11:02

Jonas Elfström


So with help of Jonas the above query reads this (using inner join):

var result = from t1 in table1
             join t2 in table2 on t1.key equals t2.key
             where  DateTime.Parse("2010-02-01") <= t1.trndate && t1.trndate <= DateTime.Parse("2010-02-28")
             group new {t1,t2} by t1.vat into g
             select new { vat = g.Key, sum = g.Sum(p => p.t1.QTY*p.t2.FLG01 + p.t1.QTY*p.t2.FLG04)};
like image 37
Savvas Sopiadis Avatar answered Feb 01 '23 11:02

Savvas Sopiadis