任何人都可以告訴我這個SQL的LINQ查詢?LINQ版本的SQL與左連接和組由
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查詢?LINQ版本的SQL與左連接和組由
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
使用它作爲
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();
您的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) };
如果你在表1的值(ID),而不是在表2(itemid的),然後t
內grouped.Sum()
將是空的,所以你需要檢查t
不是null t.price
也不是空內grouped.sum()
先生爲什麼這是一個錯誤? – user3300195
它拋出了什麼錯誤? –
vote =(g.Sum(x =>(int?)x.vote)0)/g.Count() – user3300195
此查詢標記爲解決方案,您會得到什麼樣的錯誤?提供更多信息。 – Rocketq
我試過像這樣http://stackoverflow.com/questions/21719846/linq-query-to-take-aggregate-and-normal-column-in-c-sharp-mvc – user3300195
我編輯了這個問題,使它更清楚 –