简体   繁体   中英

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.

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:

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 . I have used a CTE to avoid a brutal 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.

Also note the simpler ELSE in the CASE

you can apply GROUP BY on the CASE and find 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

sum(CASE WHEN b.ALCOHOL < 3 THEN 1 else 0 end)
....
from tbl1
group by some_col

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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