SQL 使用HAVING检查组中是否存在多个条件
示例
订单表
要检查同时订购了产品ID2和3的客户,可以使用HAVING
select customerId from orders where productID in (2,3) group by customerId having count(distinct productID) = 2
返回值:
该查询仅选择问题中带有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的记录的组。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短