[英]LINQ version of SQL with left join and group by
Can any one tell me the linq query for this sql? 谁能告诉我这个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
LINQ version of your SQL query, 您的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) };
If you have value (id) in table1 but not in table2 (itemid) then t
inside grouped.Sum()
will be null so you need to check if t
is not null and t.price
also is not null inside grouped.sum()
如果您有值(ID),在表1,但不是在表2(itemid的),那么t
内grouped.Sum()
将是空的,所以你需要检查是否t
不是null t.price
也不是里面空grouped.sum()
Use it as 用作
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.