SQL 使用HAVING检查组中是否存在多个条件

示例

订单表

顾客ID产品编号数量价钱
125100
132200
141500
21450
356700

要检查同时订购了产品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的记录的组。