[英]Case SQL and count each row
How can I get the required results below? 我如何在下面获得所需的结果? I could get all unique categories by adding
DISTINCT
, but in retrieving the total of each category the query below doesn't work. 我可以通过添加
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;
Could anyone steer me in the right direction? 有人可以引导我朝正确的方向前进吗?
You need a count()
and a group by
. 您需要一个
count()
和一个group by
。 I have used a CTE to avoid a brutal 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
Add a count and group by: 添加计数并按以下方式分组:
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
The subquery is used to simplify the GROUP BY
, because Oracle doesn't support GROUP BY 1
syntax. 子查询用于简化
GROUP BY
,因为Oracle不支持GROUP BY 1
语法。
Also note the simpler ELSE
in the CASE
还要注意
CASE
更简单的ELSE
you can apply GROUP BY
on the CASE
and find COUNT
您可以在
CASE
应用GROUP BY
并找到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;
Use a aggregate function with the same condition along with group by
like 使用条件相同的聚集函数以及
group by
sum(CASE WHEN b.ALCOHOL < 3 THEN 1 else 0 end)
....
from tbl1
group by some_col
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.