I'm playing with data from a Time Use survey as a beginner SQL user.
Gender is represented as 1's (Male) and 2's (Female), and the age of each participant is listed. I would like to divide them into age brackets with a total count, and see how many are male/female within each bracket.
What I have is this:
SELECT count(Age) as 'Total',
CASE
WHEN Age<=19 THEN 'Teen'
WHEN Age >=20 and Age<=29 THEN '20s'
WHEN Age>=30 and Age<=39 THEN '30s'
WHEN Age>=40 and Age<=49 THEN '40s'
WHEN Age>=50 and Age<=59 THEN '50s'
WHEN Age>=60 and Age<=69 THEN '60s'
WHEN Age>=70 and Age<=79 THEN '70s'
WHEN Age>=80 and Age<=89 THEN '80s'
END as 'Age',
CASE
WHEN Sex=1 THEN 'Male'
WHEN Sex=2 THEN 'Female'
END as 'Gender'
from TimeUse_Summary
Group by CASE
WHEN Age<=19 THEN 'Teen'
WHEN Age >=20 and Age<=29 THEN '20s'
WHEN Age>=30 and Age<=39 THEN '30s'
WHEN Age>=40 and Age<=49 THEN '40s'
WHEN Age>=50 and Age<=59 THEN '50s'
WHEN Age>=60 and Age<=69 THEN '60s'
WHEN Age>=70 and Age<=79 THEN '70s'
WHEN Age>=80 and Age<=89 THEN '80s'
END, Sex
order by Age
The result is exactly what I'm looking for:
|Total |Age |Gender|
|:------|:-----|------|
|173 |Teen |Male |
|175 |Teen |Female|
|438 |20s |Male |
|468 |20s |Female|
|etc. |
Should I be condensing the CASE
statements somehow?