基于COUNT的过滤行为很奇怪

时间:2013-11-21 22:32:35

标签: sql sql-server

我正在处理一个查询,该查询显示具有多个ActivityDate,TaskId和EnteredBy重复项的行:

SELECT t1.*
FROM [DailyTaskHours] t1
INNER JOIN (
    SELECT ActivityDate
        ,taskId
        ,EnteredBy
    FROM [DailyTaskHours]
    GROUP BY EnteredBy
        ,taskId
        ,ActivityDate
    HAVING COUNT(*) > 1
    ) t2 ON (
        t1.ActivityDate = t2.ActivityDate
        AND t1.taskId = t2.taskId
        AND t1.EnteredBy = t2.EnteredBy
        AND t1.Hours != 0
        )
ORDER BY TaskId

它看起来几乎正常,但有一个异常现象:

enter image description here

即使视图中只有1个taskId,也会返回上面突出显示的行(2732)。如果有>我只希望它返回1个重复的TaskId。

我做错了什么?

编辑请求选择:

SELECT ActivityDate ,taskId ,EnteredBy FROM [DailyTaskHours] where TaskId = 2732 

enter image description here

^这解释了它出现的原因,但为什么这两个10/22条目都没出现?

1 个答案:

答案 0 :(得分:1)

您的联接过滤器t1.hours != 0,但您的子查询(t2)没有相同的过滤器。像这样添加它:

SELECT t1.*
FROM [DailyTaskHours] t1
INNER JOIN (
    SELECT ActivityDate
       ,taskId
       ,EnteredBy
    FROM [DailyTaskHours]
    WHERE hours != 0
    GROUP BY EnteredBy
       ,taskId
       ,ActivityDate
    HAVING COUNT(*) > 1
    ) t2 ON (
       t1.ActivityDate = t2.ActivityDate
       AND t1.taskId = t2.taskId
       AND t1.EnteredBy = t2.EnteredBy
       AND t1.Hours != 0
       )
ORDER BY TaskId