Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL to generate an Age Pyramid

How to write a query suitable for generating an age pyramid like this: alt text

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 :)

like image 226
Starlin Avatar asked Sep 18 '25 00:09

Starlin


1 Answers

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
like image 120
Quassnoi Avatar answered Sep 19 '25 15:09

Quassnoi