linq中的GROUP BY和Have
我想将此代码转换为linq:linq中的GROUP BY和Have,linq,count,group-by,having,Linq,Count,Group By,Having,我想将此代码转换为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 sele
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()}
但这并不能正确返回COUNT
请指导我如何解决这个问题
谢谢如果没有示例数据,很难正确获取,但请尝试此片段
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
将始终返回1作为计数(*)的结果。原因是您将筛选t1.cId=2并按t1.cId分组作为第二个参数。请给出一些示例数据、预期结果和实际结果。而且,这肯定不是您的实际代码,因为它将是
Count
而不是Count
。我们不知道还有什么不准确……在第二次查询中,您按title
分组,这显然不同于按title、cId
分组。而having
子句旨在查询sum或count等聚合值,但您使用having t1.cId=2
。这应该在where
子句中完成(顺便说一下,就像您的linq查询一样)。谢谢。如果数据源中没有所有问题,那么很难构建linq。固定的。