Group rows by Year Band Interval

后端 未结 3 455
[愿得一人]
[愿得一人] 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条回答
  •  萌比男神i
    2021-01-13 14:48

    This should work - SQL Fiddle (thanks to Olaf Dietsche for showing me that this wonderful site exists):

    SELECT
        COUNT(`year`) as `count`,
        CONCAT(
            FLOOR(YEAR(`year`) / 10) * 10, 
            '-', 
            (CEIL(YEAR(`year`) / 10) * 10) - 1
        ) as `year`
    FROM
        `tbl_people`
    GROUP BY
        CONCAT(
            FLOOR(YEAR(`year`) / 10) * 10,
            '-', 
            (CEIL(YEAR(`year`) / 10) * 10) - 1
        )
    

    If the number is 1992, FLOOR(1992 / 10) will give 199, and times with 10 will give 1990. The same thing about CEIL(1992 / 10) = 200 and times 10 = 2000, minus 1, gives 1999 so the year should be 1990-1999.

提交回复
热议问题