I am facing issue in showing the data for age group by in between. Here is my query:
SELECT
CASE WHEN age BETWEEN 0 AND 18 OR age IS NULL THEN '0-18'
WHEN age BETWEEN 19 AND 30 THEN '19-30'
WHEN age BETWEEN 31 AND 35 THEN '31-35'
WHEN age BETWEEN 36 AND 50 THEN '36-50'
WHEN age BETWEEN 51 AND 100 THEN '50+'
END AS age_group,
COALESCE(COUNT(*), 0) AS count
FROM patient_registration
GROUP BY age_group;
I am trying to run the above query to show data as you can see the above query executes without any error but I need a solution for age group where the count is 0 for eg.
I don’t have record for age in between 0 to 18 it’s not showing in the output, but I want to show the record like this
age_group | count |
---|---|
0-18 | 0 |
19-30 | 192 |
31-35 | 83 |
36-50 | 223 |
50+ | 222 |
I want to show count 0 if the case doesn’t satisfy.
Here’s what I’ve tried so far:
SELECT
CASE
WHEN age BETWEEN 0 AND 18 OR age COUNT is NULL THEN '0-18'
WHEN age BETWEEN 19 AND 30 THEN '19-30'
WHEN age BETWEEN 31 AND 35 THEN '31-35'
WHEN age BETWEEN 36 AND 50 THEN '36-50'
WHEN age BETWEEN 51 AND 100 THEN '50+'
END AS age_group,
COALESCE(COUNT(*), NULL) AS count
FROM patient_registration
GROUP BY age_group;
Is there any alternate method which I can try?
3
Answers
To achieve your desired result you have to use a dummy table and then use LEFT join to generate this result –
The query will not count the rows where the age is invalid (negative, above 999) or is not set (is NULL).
Additionally you may have a table which contains a lot of ranges sets, and use it instead of synthetic table making the query dynamic.
This option might work for you. I returns all columns regardless of a count and each column IS the age-bracket in question.
Result would be