我有一个查询,我想查找其中ActivityDate和TaskId同时有多个条目的行:
SELECT
ActivityDate, taskId
FROM
[DailyTaskHours]
GROUP BY
ActivityDate, taskId
HAVING
COUNT(*) > 1
以上查询似乎有效。但是我希望所有列现在只返回两个(ActivityDate,taskId)。这不起作用:
SELECT *
FROM
[DailyTaskHours]
GROUP BY
ActivityDate, taskId
HAVING
COUNT(*) > 1
因为许多列不在group by子句中。我不希望任何列受到HAVING COUNT(*)>的影响。除ActivityDate之外的1,taskId。
我如何实现这一目标?
答案 0 :(得分:2)
WITH sel as(
SELECT
ActivityDate, taskId
FROM
[DailyTaskHours]
GROUP BY
ActivityDate, taskId
HAVING
COUNT(*) > 1
)
SELECT *
FROM [DailyTaskHours] d
INNER JOIN sel ON d.ActivityDate = sel.ActivityDate AND d.taskId = sel.taskId
答案 1 :(得分:1)
SELECT t1.*
FROM
[DailyTaskHours] t1
INNER JOIN (
SELECT
ActivityDate, taskId
FROM
[DailyTaskHours]
GROUP BY
ActivityDate, taskId
HAVING
COUNT(*) > 1
) t2 ON (
t1.ActivityDate = t2.ActivityDate AND
t1.taskId = t2.taskId
)
答案 2 :(得分:0)
以下是显示以下查询的SQL Fiddle:
SELECT DISTINCT m.*
FROM
(
SELECT s.ActivityDate, s.taskId
FROM DailyTaskHours s
GROUP BY s.ActivityDate, s.taskId
HAVING COUNT(*) > 1
) sub
JOIN DailyTaskHours m
ON m.taskId = sub.taskId
AND m.ActivityDate = sub.ActivityDate
答案 3 :(得分:0)
-- fully functional example.
DECLARE @table TABLE ( ActivityDate DATE, TaskID INT);
SET NOCOUNT ON;
INSERT @table VALUES ('01/01/2013',1);
INSERT @table VALUES ('01/02/2013',1);
INSERT @table VALUES ('01/02/2013',2);
INSERT @table VALUES ('01/03/2013',1);
INSERT @table VALUES ('01/03/2013',2);
INSERT @table VALUES ('01/03/2013',5); -- duplicate date,taskid
INSERT @table VALUES ('01/03/2013',5); -- duplicate date,taskid
SET NOCOUNT OFF;
SELECT A.*
FROM @table A
INNER JOIN (
SELECT [ActivityDate], TaskId
FROM @table
GROUP BY [ActivityDate], TaskId
HAVING Count(*) > 1
) AS B ON B.[ActivityDate]=A.ActivityDate AND B.TaskId=A.TaskId;