订单表
顾客ID | 产品编号 | 数量 | 价钱 |
---|---|---|---|
1 | 2 | 5 | 100 |
1 | 3 | 2 | 200 |
1 | 4 | 1 | 500 |
2 | 1 | 4 | 50 |
3 | 5 | 6 | 700 |
要检查同时订购了产品ID 2和3的客户,可以使用HAVING
select customerId from orders where productID in (2,3) group by customerId having count(distinct productID) = 2
返回值:
顾客ID |
---|
1 |
该查询仅选择问题中带有productID的记录,并使用HAVING子句检查具有2个productId而不是一个的组。
另一种可能性是
select customerId from orders group by customerId having sum(case when productID = 2 then 1 else 0 end) > 0 and sum(case when productID = 3 then 1 else 0 end) > 0
此查询仅选择具有至少一个产品ID为2的记录和至少一个产品ID为3的记录的组。