MySQL to create an age pyramid

How to write a query suitable for creating 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). Any field can be NULL.

I can’t understand how to handle birthdays and put them in groups of 10 years.

EDIT:

Ideally, the X axis will be percentages, not thousands :)

+3
source share
1 answer
SELECT  FLOOR((EXTRACT(YEAR FROM FROM_DAYS(DATEDIFF(NOW(), birthday))) - 4) / 10) AS age, gender, COUNT(*)
FROM    mytable
GROUP BY
        age, gender

-1aged means 0-4, 0means 4-14, etc.

This query may leave spaces if there are no people in this age group.

The same thing with percentages (of the 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
+2
source

Source: https://habr.com/ru/post/1768065/


All Articles