[英]Filter results within groups sql
In the table below, I want to know how many customers ordered lunch without a coffee .在下表中,我想知道有多少顾客点了没有咖啡的午餐。 The result would be 1, for sale ID 300, because two lunches were ordered but only one coffee.
结果将是 1,销售 ID 300,因为订购了两份午餐,但只订购了一份咖啡。
It's been 8 years since I last used SQL, How do I say “group the records by sale ID and for each group?我上次使用 SQL 已经 8 年了,我怎么说“按销售 ID 和每个组对记录进行分组? drop groups where there is no lunch or COUNT(coffee) < COUNT(lunch)"?
放弃没有午餐或 COUNT(coffee) < COUNT(lunch)" 的团体?
SALE ID![]() |
Product![]() |
---|---|
100 ![]() |
coffee![]() |
100 ![]() |
lunch![]() |
200 ![]() |
coffee![]() |
300 ![]() |
lunch![]() |
300 ![]() |
lunch![]() |
300 ![]() |
coffee![]() |
here is one way:这是一种方法:
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
You can do it with aggregation and the conditions in the HAVING clause.您可以使用聚合和 HAVING 子句中的条件来做到这一点。
This query:这个查询:
SELECT sale_id
FROM tablename
GROUP BY sale_id
HAVING SUM(product = 'lunch') > SUM(product = 'coffee');
returns all the sale_id
s that you want.返回您想要的所有
sale_id
。
This query:这个查询:
SELECT DISTINCT COUNT(*) OVER () counter
FROM tablename
GROUP BY sale_id
HAVING SUM(product = 'lunch') > SUM(product = 'coffee');
returns the number of sale_id
s that you want.返回您想要的
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.