2013-02-12 97 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