Group Ranges per Year Band Interval

advertisements

I have a table (tbl_people), in this table I have a datetime field I want to group and count the records in groups of 10 years... The result should be something like:
| count    | year           |
| 1000     | 1980-1989 |
| 250       | 1990-1999 |

I can write multiple queries to do it, but that means I'll have to write different queries for each range. Is there a way to dynamically increment from the least year upwards (10 year intervals) and count the number of records within the intervals?


Try this SQL Fiddle

select count(*), decade, decade + 9
from (select floor(year(`year`) / 10) * 10 as decade
      from tbl_people) t
group by decade

or this SQL Fiddle, if you want the decade in one column

select count(*) as count, concat(decade, '-', decade + 9) as year
from (select floor(year(`year`) / 10) * 10 as decade
      from tbl_people) t
group by decade