2014-02-12 27 views
1

任何人都可以告訴我這個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 
+0

此查詢標記爲解決方案,您會得到什麼樣的錯誤?提供更多信息。 – Rocketq

+0

我試過像這樣http://stackoverflow.com/questions/21719846/linq-query-to-take-aggregate-and-normal-column-in-c-sharp-mvc – user3300195

+0

我編輯了這個問題,使它更清楚 –

回答

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(); 
+0

如何乘以那個總和? – user3300195

+0

你想要增加什麼? –

+0

你是在說這個.. sum = 5 * t1g.Sum(p => p.price?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) }; 

如果你在表1的值(ID),而不是在表2(itemid的),然後tgrouped.Sum()將是空的,所以你需要檢查t不是null t.price也不是空內grouped.sum()

+0

先生爲什麼這是一個錯誤? – user3300195

+0

它拋出了什麼錯誤? –

+0

vote =(g.Sum(x =>(int?)x.vote)0)/g.Count() – user3300195