Case SQL并计算每一行

时间:2017-02-10 13:56:50

标签: sql oracle count group-by

如何在下面获得所需的结果?我可以通过添加DISTINCT来获取所有唯一类别,但在检索每个类别的总计时,下面的查询无效。

表结构:BEER

ID | NAME | TYPE | ALCOHOL | 

必填结果

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

我的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;

有人能引导我朝着正确的方向前进吗?

4 个答案:

答案 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