You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL中如何通过HAVING子句筛选仅供应BLACK咖啡的位置?

解决方案:筛选仅供应BLACK咖啡的位置

要实现只返回仅供应'BLACK'咖啡、完全不供应'LATTE'的位置,你需要在HAVING子句中同时满足两个核心条件:

  1. 该位置没有任何'LATTE'类型的咖啡
  2. 该位置至少有'BLACK'类型的咖啡

方法一:通过条件计数精准过滤

修改你的查询,在HAVING中添加条件计数逻辑,直接判断两种咖啡的存在情况:

select stn.table_id, st.coffee_number, location
from some_table_test st
join some_table_test_coffee s on st.coffee_id = s.coffee_id
join some_table_number stn on stn.coffee_number = st.coffee_number
group by location, st.coffee_number, stn.table_id
having 
  -- 确保该分组下没有LATTE咖啡
  count(case when coffee_type = 'LATTE' then 1 end) = 0
  -- 确保该分组下至少有BLACK咖啡
  and count(case when coffee_type = 'BLACK' then 1 end) > 0;

方法二:利用聚合函数限定唯一类型

如果你的场景中咖啡类型只有'BLACK'和'LATTE'两种,也可以简化为:

select stn.table_id, st.coffee_number, location
from some_table_test st
join some_table_test_coffee s on st.coffee_id = s.coffee_id
join some_table_number stn on stn.coffee_number = st.coffee_number
group by location, st.coffee_number, stn.table_id
having 
  -- 只有一种咖啡类型
  count(distinct coffee_type) = 1
  -- 且该类型是BLACK
  and max(coffee_type) = 'BLACK';

验证结果

执行上述任意查询后,返回结果会自动排除位置G的行,仅保留符合要求的位置D的数据:

| table_id | coffee_number | location |
|----------|---------------|----------|
|   123456 |            10 |        D |
|    98764 |            11 |        D |

逻辑说明

  • 方法一的条件计数更通用,即使后续新增其他咖啡类型也能正常工作,不会误判
  • 方法二依赖咖啡类型只有两种的前提,代码更简洁但场景受限

内容的提问来源于stack exchange,提问作者Sachin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 11:52:57