views:

26

answers:

1

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

+1  A: 
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
Quassnoi
Thanks for your answer! Unfortunatley the age is not working, it just returns 0 :S
Starlin
@Starlin: please post a sample record which you think should return another value
Quassnoi
You are right, my mistake :)
Starlin