如何在下面获得所需的结果?我可以通过添加DISTINCT
来获取所有唯一类别,但在检索每个类别的总计时,下面的查询无效。
ID | NAME | TYPE | ALCOHOL |
category | total
----------------------------
Light | 34
Medium | 2
Normal | 3
Heavy | 4
Knock out | 5
SELECT
CASE WHEN b.ALCOHOL < 3 THEN 'Light'
WHEN b.ALCOHOL < 5 THEN 'Medium'
WHEN b.ALCOHOL < 7 THEN 'Normal'
WHEN b.ALCOHOL < 9 THEN 'Heavy'
WHEN b.ALCOHOL >= 9 THEN 'Knock out'
END AS category
FROM BEER b;
有人能引导我朝着正确的方向前进吗?
答案 0 :(得分:3)
您需要count()
和group by
。我使用过CTE来避免残酷的group by
with CTE as
(
SELECT
CASE WHEN b.ALCOHOL < 3 THEN 'Light'
WHEN b.ALCOHOL < 5 THEN 'Medium'
WHEN b.ALCOHOL < 7 THEN 'Normal'
WHEN b.ALCOHOL < 9 THEN 'Heavy'
WHEN b.ALCOHOL >= 9 THEN 'Knock out'
END AS category,
b.Alcohol
FROM BEER b
)
select category, count(alcohol)
from CTE
group by category
答案 1 :(得分:2)
按以下方式添加计数和分组:
SELECT Category, COUNT(*) AS Total FROM (
SELECT
CASE WHEN b.ALCOHOL < 3 THEN 'Light'
WHEN b.ALCOHOL < 5 THEN 'Medium'
WHEN b.ALCOHOL < 7 THEN 'Normal'
WHEN b.ALCOHOL < 9 THEN 'Heavy'
ELSE 'Knock out'
END AS Category
FROM BEER) b
GROUP BY Category
子查询用于简化GROUP BY
,因为Oracle不支持GROUP BY 1
语法。
另请注意ELSE
CASE
答案 2 :(得分:1)
您可以在GROUP BY
上应用CASE
并找到COUNT
SELECT
CASE WHEN b.ALCOHOL < 3 THEN 'Light'
WHEN b.ALCOHOL < 5 THEN 'Medium'
WHEN b.ALCOHOL < 7 THEN 'Normal'
WHEN b.ALCOHOL < 9 THEN 'Heavy'
WHEN b.ALCOHOL >= 9 THEN 'Knock out'
END AS category,
count(*) total
FROM BEER b
GROUP BY
CASE WHEN b.ALCOHOL < 3 THEN 'Light'
WHEN b.ALCOHOL < 5 THEN 'Medium'
WHEN b.ALCOHOL < 7 THEN 'Normal'
WHEN b.ALCOHOL < 9 THEN 'Heavy'
WHEN b.ALCOHOL >= 9 THEN 'Knock out'
END;
答案 3 :(得分:0)
使用具有相同条件的聚合函数以及group by
sum(CASE WHEN b.ALCOHOL < 3 THEN 1 else 0 end)
....
from tbl1
group by some_col