I use the following query to calculate the age of people from their dob and then group the ages in ten year intervals to make a frequency chart.
I'd prefer the user to be able to choose the bin size instead of always having to use 10 years, eg maybe group the ages in 5 year intervals, 20 year intervals or any arbitrary range.
How should I re-write the query so that the bin size (currently 10 years) can be passed as a parameter or maybe picked up from another table that is pre-populated with the bins just before running the query?
Obviously I won't be able to use a hard coded CASE in the same way, if at all. Can it be done?
SELECT
CASE
WHEN age = -1 THEN 0 -- null dob
WHEN age >= 0 AND age < 11 THEN 1
WHEN age >= 11 AND age < 21 THEN 2
WHEN age >= 21 AND age < 31 THEN 3
WHEN age >= 31 AND age < 41 THEN 4
WHEN age >= 41 AND age < 51 THEN 5
WHEN age >= 51 AND age < 61 THEN 6
WHEN age >= 61 AND age < 71 THEN 7
WHEN age >= 71 AND age < 81 THEN 8
WHEN age >= 81 AND age < 91 THEN 9
WHEN age >= 91 AND age < 101 THEN 10
WHEN age > 100 THEN 11
END AS Age_Group,
COUNT(age) AS Number_In_Group
FROM
-- this sub query calculates the age from the dob
-- returning -1 if dob is null
(SELECT
IFNULL(
DATE_FORMAT(NOW(), '%Y')
- DATE_FORMAT(dob, '%Y')
- (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(dob, '00-%m-%d'))
, - 1
) AS age
FROM
people
) AS table_age
GROUP BY Age_Group
This produces the following typical output
Age_Group Number_In_Group
0 55
2 1
3 37
4 47
5 51
6 112
7 139
8 70
9 30
10 6