2013-02-12 78 views
1

我有這樣一個表:如何從具有唯一ID的行中獲取ID?

id | customer_id | code 
----------------------- 
1 | 1   | A 
2 | 1   | B 
3 | 2   | A 
4 | 2   | D 
5 | 3   | B 
6 | 3   | C 
6 | 3   | D 

我需要返回所有客戶ID等於A和B在上面的數據代碼的SQL查詢,這隻會CUSTOMER_ID 1

如果代碼是各自的專欄,這將是一個簡單的查詢:SELECT DISTINCT customer_id FROM tablename WHERE code = A AND code = B。但是,我似乎無法將它製作成多行。

回答

4

您可以使用GROUP BY customer_idHAVING條款:

select customer_id 
from yourtable 
where code in ('A', 'B') 
group by customer_id 
having count(distinct code) = 2 

SQL Fiddle with Demo

如果你想從你的表中返回數據,那麼你可以展開查詢:

select * 
from yourtable t1 
where exists (select customer_id 
       from yourtable t2 
       where code in ('A', 'B') 
       and t1.customer_id = t2.customer_id 
       group by customer_id 
       having count(distinct code) = 2) 

請參閱SQL Fiddle with Demo

+0

謝謝!我正在做一個SELECT嵌套SELECT,知道必須有更好的方法。 – Ryre 2013-02-12 19:50:34

+0

@ Toast樂意幫忙。僅供參考,如果您想從yourtable返回更多數據,您可以在'WHERE EXISTS'中使用它。看我的編輯 – Taryn 2013-02-12 19:55:05

1
select customer_id 
from tablename 
where code in ('A', 'B') 
group by customer_id 
having count(*) > 1