0

I apologize if this question is vague, I'm new to SQL and am having some trouble. I'm trying to find the number of people within each weight group. Count that number and display the number of each class.

I think my issue lies within the THEN expression. Do I need to create a variable for each weight group to compare to?

Thank you

SELECT 
(CASE WHEN pl_weight <180 THEN 1
WHEN pl_weight >=180 AND pl_weight <200 THEN 2
WHEN pl_weight >=200 AND pl_weight <220 THEN 3
ELSE 4 END),
count(1) "Less than 280", count(2)"180-200", count(3)"200-220",count(4)"More than 220"  
FROM dl_player
GROUP BY (CASE WHEN pl_weight <180 THEN 1
WHEN pl_weight >=180 AND pl_weight <200 THEN 2
WHEN pl_weight >=200 AND pl_weight <220 THEN 3
ELSE 4
END));

2 Answers 2

1

One way to do this is to use conditional aggregation like this:

SELECT 
    SUM(CASE WHEN "pl_weight" <180 THEN 1 ELSE 0 END) AS "Less than 280",
    SUM(CASE WHEN "pl_weight" >=180 AND "pl_weight" <200 THEN 1 ELSE 0 END) AS "180-200",
    SUM(CASE WHEN "pl_weight" >=200 AND "pl_weight" <220 THEN 1 ELSE 0 END) AS "200-220",
    SUM(CASE WHEN "pl_weight" >=220 THEN 1 ELSE 0 END) AS "More than 220"  
FROM dl_player

Sample result:

| LESS THAN 280 | 180-200 | 200-220 | MORE THAN 220 |
|---------------|---------|---------|---------------|
|             4 |       1 |       3 |             3 |

Sample SQL Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this helped. I assumed you had to use Group By, so that was causing me problems.
@user2348621 If my answer help solve your problem please consider marking it as accepted. :)
1

COUNT() doesn't work the way you want it to; it counts rows or, more specifically, the # of rows for which the value inside is not NULL. You might do this using conditional aggregation, as in @jpw's answer, or you might do it using a subquery:

SELECT weight, COUNT(*) FROM (
    SELECT CASE WHEN pl_weight <180 THEN "Less than 180"
        WHEN pl_weight >=180 AND pl_weight <200 THEN "180-200"
        WHEN pl_weight >=200 AND pl_weight <220 THEN "200-220"
        ELSE "More than 220" END AS weight
      FROM dl_player
) GROUP BY weight;

By the way, I'm not sure if you noticed, but you have an off-by-one error in your final case. It will return 4, or More than 220, for values of 220 or more.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.