在下表中,我想知道有多少顧客點了沒有咖啡的午餐。結果將是 1,銷售 ID 300,因為訂購了兩份午餐,但只訂購了一份咖啡。
我上次使用 SQL 已經 8 年了!我怎么說“按銷售 ID 對記錄進行分組,并且對于每個組,洗掉沒有午餐或 COUNT(coffee) < COUNT(lunch) 的組”?
| 銷售編號 | 產品 |
|---|---|
| 100 | 咖啡 |
| 100 | 午餐 |
| 200 | 咖啡 |
| 300 | 午餐 |
| 300 | 午餐 |
| 300 | 咖啡 |
uj5u.com熱心網友回復:
這是一種方法:
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
uj5u.com熱心網友回復:
您可以使用聚合和 HAVING 子句中的條件來做到這一點。
這個查詢:
SELECT sale_id
FROM tablename
GROUP BY sale_id
HAVING SUM(product = 'lunch') > SUM(product = 'coffee');
回傳所有sale_id你想要的 s。
這個查詢:
SELECT DISTINCT COUNT(*) OVER () counter
FROM tablename
GROUP BY sale_id
HAVING SUM(product = 'lunch') > SUM(product = 'coffee');
回傳sale_id您想要的 s 數量。
請參閱演示。
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410111.html
標籤:
