2014-12-04 53 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