Linq to SQL相当于SUM GROUP BY SQL语句

时间:2010-02-10 22:34:11

标签: sql linq-to-sql group-by sum

我很难弄清楚如何将这个简单的SQL语句转换为(c#)linq到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

感谢任何帮助

2 个答案:

答案 0 :(得分: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,因为我只在对象上试过它。

答案 1 :(得分:2)

因此,在Jonas的帮助下,上述查询读取此内容(使用内部联接):

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