[英]Filter results within groups sql
在下表中,我想知道有多少顾客点了没有咖啡的午餐。 结果将是 1,销售 ID 300,因为订购了两份午餐,但只订购了一份咖啡。
我上次使用 SQL 已经 8 年了,我怎么说“按销售 ID 和每个组对记录进行分组? 放弃没有午餐或 COUNT(coffee) < COUNT(lunch)" 的团体?
销售编号 | 产品 |
---|---|
100 | 咖啡 |
100 | 午餐 |
200 | 咖啡 |
300 | 午餐 |
300 | 午餐 |
300 | 咖啡 |
这是一种方法:
select count(*) from (
select saleID
from tablename
group by saleID
having sum(case when product ='coffee' then 1 else 0 end) = 0
and sum(case when product ='lunch' then 1 else 0 end) = 1
) t
您可以使用聚合和 HAVING 子句中的条件来做到这一点。
这个查询:
SELECT sale_id
FROM tablename
GROUP BY sale_id
HAVING SUM(product = 'lunch') > SUM(product = 'coffee');
返回您想要的所有sale_id
。
这个查询:
SELECT DISTINCT COUNT(*) OVER () counter
FROM tablename
GROUP BY sale_id
HAVING SUM(product = 'lunch') > SUM(product = 'coffee');
返回您想要的sale_id
的数量。
请参阅演示。
select * from (
select
saleID, sum(case when product ='coffee' then 1 else 0 end) as coffee,
sum(case when product ='lunch' then 1 else 0 end) lunch
from tablename
group by saleID
having sum(case when product ='lunch' then 1 else 0 end) >= 1
) t
where lunch > coffee
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.