简体   繁体   English

编写SQL案例并计数每一行

[英]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来获得所有唯一类别,但是在检索每个类别的总数时 ,下面的查询不起作用。

Table structure: BEER 表结构:啤酒

ID | NAME | TYPE | ALCOHOL | 

Required Result 所需结果

category   |  total
----------------------------
Light      | 34
Medium     | 2
Normal     | 3
Heavy      | 4
Knock out  | 5

My SQL Query: 我的SQL查询:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM