Linq to SQL equivalent of SUM GROUP BY SQL expression

I find it difficult to understand how to translate this simple SQL statement in (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

+4
source share
2 answers

I'm still learning LINQ, but it works

 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 this translates LINQ to SQL well, because I only tried it on objects.

+7
source

So, using Jonas, the above query reads this (using an internal 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)}; 
+2
source

Source: https://habr.com/ru/post/1300926/


All Articles