我从表中获取代码列表及其各自的计数。我不需要在SQL中使用distinct,但是如果我不在LINQ查询中添加它,我会得到很多欺骗行。
那么,为什么我需要对LINQ查询进行不同的调用?
SQL
SELECT COUNT(*) AS ServiceCodeCnt, d.ServiceCode
FROM dbo.BackOrderItem d
GROUP BY d.ServiceCode, d.Model
HAVING d.Model ='UUTTIISJWW'
LINQ(通过LINQpad)
void Main()
{
var retval = (from a in BackOrderItems where a.Model == "UUTTIISJWW"
group a by new {a.ServiceCode, a.Model} into grp1
from b in grp1
select new {Code = b.ServiceCode, Count = grp1.Count( ) }).ToList().Distinct();
retval.Dump();
}
答案 0 :(得分:3)
陈述......
from b in grp1
...使分组变得平坦。因此,您选择每个组中的所有单独行,每个行都包含其组的计数。
只需删除此语句即可:
var retval = (from a in BackOrderItems where a.Model == "UUTTIISJWW"
group a by a.ServiceCode into grp1
select new
{
Code = grp1.Key,
Count = grp1.Count()
})
.ToList();
请注意,我还从分组中删除了Model
。没有必要,因为您只过滤了一个Model
。