如何在Linq to SQL中使用distinct with group

时间:2010-08-26 20:32:16

标签: c# .net linq 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]

5 个答案:

答案 0 :(得分:5)

我认为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()
        };

答案 1 :(得分:0)

根据这篇文章,您的代码看起来是正确的:

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

您是否尝试过检查生成的SQL?

答案 2 :(得分:0)

在生成的SQL中似乎有一大堆goop来处理GroupID为NULL。如果可能的话?如果没有,请尝试更改定义,使其为NOT NULL。

答案 3 :(得分:0)

尝试使用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()
    };

答案 4 :(得分:0)

您确定数据库完整性正确吗?无论如何也许你应该试试这个: 我不知道一个小组是如何空洞的,但这似乎是你的问题。

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() 
                     });