How to write a query suitable for generating an age pyramid like this:
I have a table with a DATE field containing their birthday and a BOOL field containing the gender (male = 0, female = 1). Either field can be NULL.
I can't seem to work out how to handle the birthdays and put them into groups of 10 years.
EDIT:
Ideally the X axis would be percent rather than thousands :)
SELECT FLOOR((EXTRACT(YEAR FROM FROM_DAYS(DATEDIFF(NOW(), birthday))) - 4) / 10) AS age, gender, COUNT(*)
FROM mytable
GROUP BY
age, gender
-1
in age means 0-4
, 0
means 4-14
etc.
This query may leave gaps if there are no persons within a given age group.
The same with percents (from total population):
SELECT FLOOR((EXTRACT(YEAR FROM FROM_DAYS(DATEDIFF(NOW(), birthday))) - 4) / 10) AS age, gender,
COUNT(*) /
(
SELECT COUNT(*)
FROM mytable
)
FROM mytable
GROUP BY
age, gender
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With