You can sort of get what you want with a somewhat ugly use of the CASE expression:
Code:
SELECT CASE WHEN age BETWEEN 0 AND 4 THEN '0-4'
WHEN age BETWEEN 5 AND 9 THEN '5-9'
WHEN age BETWEEN 10 AND 14 THEN '10-14'
WHEN age BETWEEN 15 AND 19 THEN '15-19'
WHEN age BETWEEN 20 AND 24 THEN '20-24'
ELSE '25 plus' END AS AgeGroup,
COUNT(*) AS Totals
FROM YourTable
GROUP BY CASE WHEN age BETWEEN 0 AND 4 THEN '0-4'
WHEN age BETWEEN 5 AND 9 THEN '5-9'
WHEN age BETWEEN 10 AND 14 THEN '10-14'
WHEN age BETWEEN 15 AND 19 THEN '15-19'
WHEN age BETWEEN 20 AND 24 THEN '20-24'
ELSE '25 plus' END;
but this will not return any groups with 0 members (e.g. group '5-9').
A better solution might be to create a table which defines the groups you are interested in. Perhaps a table like:
Code:
CREATE TABLE Intervals (
LoRange int NOT NULL PRIMARY KEY,
HiRange int NOT NULL ,
Descr char(10) NOT NULL);
and populate it appropriately. This has the advantage of making your grouping considerably more flexible. Pick a suitably high value for the 'HiRange' of the last group. Then the query might be:
Code:
SELECT descr AS AgeGroup, COUNT(age) as totals
FROM Intervals LEFT JOIN YourTable ON YourTable.Age BETWEEN Intervals.LoRange AND Intervals.HiRange
GROUP BY descr
This of course begs the question of why you have a dependent value like 'Age' stored in your table in the first place. The value is dependent because an age is always relative to the day on which you compute it. Your design means that you will have to have some process which runs periodically which updates the 'Age' column. If you forget to run it, your data is corrupt. Not good. Better to store the date of birth and compute the age whenever you need it.
Jeff Mason
Custom Apps, Inc.
www.custom-apps.com