MySQL Group By Dates Between

前端 未结 3 1646
醉梦人生
醉梦人生 2020-12-21 09:18

Is there a way to group records that fall between two dates?

For example, my table has records that look like this:

rid     stamp                   u         


        
3条回答
  •  [愿得一人]
    2020-12-21 09:40

    In slight combination of the others... you can expand the case structure for however range specific you want. The group by respects the "ordinal" column 1 position so you don't have to copy the same case condition in the group by clause. Additionally, I threw in the Order by to have same context of the case since it would otherwise order the results alphabetically. You can order by whatever you wanted... even in reverse if you wanted most current date activity listed first.

    SELECT
          case when stamp between "2005-07-01" and "2006-02-01"
                  then "July 2005 - January 2006   "
               when stamp between "2006-02-01" and "2006-08-01"
                  then "February 2006 - August 2006"
               else    "After August 2006          "
          end as GroupColumn,
          count(*) as TotalPerGroup
       from  
          table
       where 
          date >= '2005-07-01'
       group by 
          1
       order by 
          case when stamp between "2005-07-01" and "2006-02-01"
                  then 1
               when stamp between "2006-02-01" and "2006-08-01"
                  then 2
               else    3
          end 
    

提交回复
热议问题