我正在尝试从一个表中选择具有重复项的行,但也会根据另一列限制行。它似乎没有正常工作。
select Id,Terms from QueryData
where Track = 'Y' and Active = 'Y'
group by Id,Terms
having count(Terms) > 1
如果我删除它正常工作的地方,但我只需将其限制为这些行。
ID Terms Track Active
100 paper Y Y
200 paper Y Y
100 juice Y Y
400 orange N N
1000 apple Y N
理想情况下,查询应该返回前两行。
答案 0 :(得分:7)
SELECT Id, Terms, Track, Active
FROM QueryData
WHERE Terms IN (
SELECT Terms
FROM QueryData
WHERE Track = 'Y' and Active = 'Y'
GROUP BY Terms
HAVING COUNT(*) > 1
)
SQLFiddle上的演示
答案 1 :(得分:1)
不要完全得到你正在做的事情。您在count(Terms)
中使用having
,但Terms
条款中包含select
。这意味着每个记录count(Terms)
将为1.可能您必须从Terms
列表中排除select
。
老实说,我复制了你的表和查询,它不起作用。
可能this正是您要找的(?):
select Id, count(Terms) from QueryData
where Track = 'Y' and Active = 'Y'
group by Id
having count(Terms) > 1
答案 2 :(得分:1)
这将返回符合条件的所有重复条款:
select Terms
from QueryData
where Track = 'Y' and Active = 'Y'
group by Terms
having count(*) > 1
http://sqlfiddle.com/#!3/18a57/2
如果您想了解这些条款的所有详细信息,可以加入此结果。
;with dups as (
select Terms
from QueryData
where Track = 'Y' and Active = 'Y'
group by Terms
having count(*) > 1
)
select
qd.ID, qd.Terms, qd.Track, qd.Active
from
QueryData qd join
dups d on qd.terms = d.terms