1

我有一张这样的桌子:

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

我需要一个 SQL 查询,它返回代码等于 A 和 B 的所有客户 ID。在上面的数据中,这只会是 customer_id 1。

如果代码是各自的列,这将是一个简单的查询:SELECT DISTINCT customer_id FROM tablename WHERE code = A AND code = B. 但是,我似乎无法在多行上制作它。

4

2 回答 2

4

您可以使用GROUP BY customer_idwithHAVING子句:

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

请参阅带有演示的 SQL Fiddle

如果要从表中返回更多数据,则可以将查询扩展为:

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

于 2013-02-12T18:47:48.327 回答
1
select customer_id
from tablename
where code in ('A', 'B')
group by customer_id
having count(*) > 1
于 2013-02-12T18:48:39.397 回答