在组内过滤结果 sql

Filter results within groups sql

在下面的table中,我想知道有多少顾客点了没有咖啡的午餐。结果将是 1,销售 ID 300,因为订购了两份午餐,但只订购了一份咖啡。

距离上次使用已经8年了SQL!我怎么说“按销售 ID 对记录进行分组,对于每个组,删除没有午餐或 COUNT(coffee) < COUNT(lunch) 的组”?

SALE ID Product
100 coffee
100 lunch
200 coffee
300 lunch
300 lunch
300 coffee

这是一种方法:

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'); 

returns 所有你想要的 sale_id

这个查询:

SELECT DISTINCT COUNT(*) OVER () counter
FROM tablename
GROUP BY sale_id
HAVING SUM(product = 'lunch') > SUM(product = 'coffee');

returns 您想要的 sale_id 个数。

参见demo

select count(*) from (
  --in this subquery calculate counts and ignore items that haven't any lunch
   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  --Here we are ignoring all items haven't any lunch
) t
where lunch > coffee -- we check second condition be ok