具有左连接和分组依据的SQL的LINQ版本

时间:2014-02-12 06:26:44

标签: c# sql linq

任何人都能告诉我这个sql的linq查询吗?

select 
  t1.item, 
  IsNull(sum(t2.price), 0) total
from table1 t1
left join table2 t2
  on t1.id = t2.itemid
group by t1.item

2 个答案:

答案 0 :(得分:0)

SQL查询的LINQ版本,

var resutl = from t1 in objtable1
                     join t2 in objtable2 on t1.id equals t2.itemid into j1
                     from j2 in j1.DefaultIfEmpty()
                     group j2 by t1.item into grouped
                     select new { item = grouped.Key,  sum =  grouped.Sum(t => t != null ? (t.price ??0 ) : 0) };

如果table1中有值(id)但table2(itemid)中没有,那么t内的grouped.Sum()将为null,因此您需要检查t是否为空且{在t.price

中{1}}也不为空

答案 1 :(得分:0)

将其用作

var result = (from t1 in table1 
                      join t2 in table2 on t1.id equals t2.itemId
                     into t2d from td in t2d.DefaultIfEmpty()
                     group t1 by t1.item into t1g select new {item=t1g.key, sum =t1g.Sum(p=>p.price??0)} ).ToList();