7

我正在尝试从表中选择一列中有重复项但也限制基于另一列的行的行。它似乎无法正常工作。

select Id,Terms from QueryData 
where Track = 'Y' and Active = 'Y'
group by Id,Terms
having count(Terms) > 1

如果我删除where它可以正常工作,但我需要将其限制为仅这些行。

ID      Terms     Track    Active
100     paper     Y        Y
200     paper     Y        Y
100     juice     Y        Y
400     orange    N        N
1000    apple     Y        N

理想情况下,查询应该返回前 2 行。

4

3 回答 3

8
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上的演示

数据:

ID      Terms     Track    Active
100     paper     Y        Y
200     paper     Y        Y
100     juice     Y        Y
400     orange    N        N
1000    apple     Y        N

结果:

Id      Terms     Track    Active
100     paper     Y        Y
200     paper     Y        Y
于 2012-12-17T22:36:09.497 回答
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

http://sqlfiddle.com/#!3/18a57/5

于 2012-12-17T19:57:59.473 回答
1

不要完全明白你在做什么。但是,您在您的子句中使用count(Terms)in 。这意味着每条记录将是 1。可能您必须从列表中排除。老实说,我复制了您的表格和查询,但它不起作用。havingTermsselectcount(Terms)Termsselect

可能就是您正在寻找的(?):

select Id, count(Terms) from QueryData 
where Track = 'Y' and Active = 'Y'
group by Id
having count(Terms) > 1
于 2012-12-17T19:57:03.340 回答