2010-02-10 84 views
4

我有一個很難搞清楚如何翻譯這個簡單的SQL語句(C#)的LINQ to SQL:LINQ到SQL相當於SUM GROUP BY 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 

任何幫助表示讚賞

回答

7

我還在學習LINQ但這似乎工作

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)}; 

我希望在轉換很好地LINQ to SQL的,因爲我只試過的對象。

+0

...是的,它確實工作了!我想我永遠不會習慣這種尤達語言。非常感謝 – 2010-02-11 07:58:50

2

因此,與喬納斯的幫助下,上述查詢讀這個(使用內部連接):

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)};