Group rows by Year Band Interval

后端 未结 3 426
[愿得一人]
[愿得一人] 2021-01-13 14:22

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:

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 14:52

    First calculate the decade for each row

    select floor(year(`year`) / 10) * 10 as decade
    from tbl_people
    

    and then use this intermediate result for counting 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
    

提交回复
热议问题