2012-08-15 149 views
0

HAVING我想這個代碼轉換爲LINQ:GROUP BY和LINQ

select t1.title, COUNT(*)as num 
from t1 INNER join t2 on t2.gId = t1.Id 
group by t1.title, t1.cId 
having t1.cId = 2 

我想這下面的代碼:

from p in db.t1s join r in db.t2s on p.Id equals r.gId 
where p.cId == 2 
group p by p.title into g 
select new{ name = from o in g select o.title, num = g.Count()} 

但是,這並不正確返回計數。

請指導我怎樣才能解決這個問題

感謝

+2

請提供一些樣本數據,預期結果和實際結果。此外,這絕對不是你的實際代碼,因爲它會是'Count'而不是'count'。我們不能說什麼*其他*不準確...... – 2012-08-15 12:00:18

+0

在你的第二個查詢中,你用'title'分組,這顯然不同於'title,cId'分組。 – usr 2012-08-15 12:39:03

+1

而'having'子句用於查詢彙總值,例如sum或count,但是您使用'having t1.cId = 2'。這應該在'where'子句中完成(順便說一句,你的linq查詢會這樣做)。 – 2012-08-15 13:23:11

回答

0

無採樣數據它很難得到它的權利,但嘗試這個片段

from p in db.t1s 
join r in db.t2s on p.Id equals r.gId 
where p.cId == 2 
group p by new {p.title, p.cId} into grouped 
select new{ name = grouped.Key.title, num = grouped.Count()} 

此外,請注意,這個SQL語句:

select t1.title, COUNT(*)as num 
from t1 INNER join t2 on t2.gId = t1.Id 
group by t1.title, t1.cId 
having t1.cId = 2 

由於COUNT(*)將始終返回1。原因是你有過濾t1.cId = 2和t1.cId分組作爲第二個參數。

+0

您可以使用'g.Key.title'。 – 2012-08-15 13:43:35

+0

謝謝。如果沒有數據源頭腦的問題,很難構建linq。固定。 – 2012-08-15 13:49:20

+0

非常感謝你 – user1495593 2012-08-15 13:55:48