[英]How to use distinct with group by in Linq to SQL
我正在尝试将以下sql转换为Linq 2 SQL:
select groupId, count(distinct(userId)) from processroundissueinstance
group by groupId
这是我的代码:
var q = from i in ProcessRoundIssueInstance
group i by i.GroupID into g
select new
{
Key = g.Key,
Count = g.Select(x => x.UserID).Distinct().Count()
};
当我运行代码时,我不断获得无效的GroupID。 有任何想法吗? 看起来不同的是搞砸了......
这是生成的sql:
SELECT [t1].[GroupID] AS [Key], (
SELECT COUNT(*)
FROM (
SELECT DISTINCT [t2].[UserID]
FROM [ProcessRoundIssueInstance] AS [t2]
WHERE (([t1].[GroupID] IS NULL) AND ([t2].[GroupID] IS NULL))
OR (([t1].[GroupID] IS NOT NULL)
AND ([t2].[GroupID] IS NOT NULL)
AND ([t1].[GroupID] = [t2].[GroupID]))
) AS [t3]
) AS [Count]
FROM (
SELECT [t0].[GroupID]
FROM [ProcessRoundIssueInstance] AS [t0]
GROUP BY [t0].[GroupID]
) AS [t1]
我认为Basiclife很接近,但是检查id是否为空可能不是问题或者足够,你应该检查以确保它在执行组之前不是null,因为你说它是一个可以为空的字段。 否则它看起来是正确的,如果你遇到问题,你可能有错误的数据,或者它是一个错误或没有完全实现的Linq to SQL功能,你可能想尝试Linq to Entity。
var q = from i in ProcessRoundIssueInstance
where i.GroupID != null
&& i.GroupID != string.Empty
group i by i.GroupID into g
select new
{
Key = g.Key,
Count = g.Select(x => x.UserID).Distinct().Count()
};
在生成的SQL中似乎有一大堆goop来处理GroupID为NULL。 如果可能的话? 如果没有,请尝试更改定义以使其为NOT NULL。
尝试使用where子句来消除加入后的虚假ID ...
var q = from i in ProcessRoundIssueInstance
where i.GroupID != ""
group i by i.GroupID into g
select new
{
Key = g.Key,
Count = g.Select(x => x.UserID).Distinct().Count()
};
您确定数据库完整性正确吗? 无论如何也许你应该尝试这个:我不知道一个小组是如何空的,但这似乎是你的问题。
ProcessRoundIssueInstance.Where(i => i.GroupId != null)
.GroupBy(i => i.GroupID)
.Select(group => new
{
Key = group.Key,
Count = group.SingleOrDefault() == null ? 0 :
group.SingleOrDefault().Select( item => item.UserID).Distinct().Count()
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.