[英]LINQ version of SQL with left join and group by
誰能告訴我這個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
您的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) };
如果您有值(ID),在表1,但不是在表2(itemid的),那么t
內grouped.Sum()
將是空的,所以你需要檢查是否t
不是null t.price
也不是里面空grouped.sum()
用作
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.