2014-12-04 26 views
1

我有一个连接表与两列组合主键。 我想查询所有条目具有计数和列查询的组合

columnA having count > 1 

columnB = value1 and value2 

我的查询到目前为止是这样的

select 
    columnA 
from tableA 
where columnB = 1 and 
columnA in (
     select 
      columnA 
     from tableA 
     group by columnA 
     having count(columnA) > 1) 

select 
     columnA 
    from tableA 
    where columnB = 2 and 
    columnA in (
      select 
       columnA 
      from tableA 
      group by columnA 
      having count(columnA) > 1) 

我如何可以查询

...columnB = 1 and columnB = 2 and columnA in (select .... 

回答

2
select columnA 
from tableA 
where columnB in (1,2) 
group by columnA 
having count(distinct columnB) = 2 

有两个值12columnB fullfills自动count(columnA) > 1

如果你想要么columnB条件(columnB有2个值)columnA条件,那么做

select columnA 
from tableA 
group by columnA 
having count(*) > 1 
or count(distinct columnB) = 2 

columnB必须12

select columnA 
from tableA 
group by columnA 
having count(*) > 1 
or 
( 
    sum(case when columnB = 1 then 1 else 0 end) > 0 and 
    sum(case when columnB = 2 then 1 else 0 end) > 0 
) 
+0

感谢的作品,但如果我想查询计数(columnA)= 2? – Markus 2014-12-04 10:12:55

+0

然后将'count(columnA)= 2'加到最后。 – 2014-12-04 10:15:01

+0

但不给我这也columnB组合(1,3),因为(1,2)中的列B是一个或链接是不是? – Markus 2014-12-04 10:17:31