按年分组

时间:2018-01-16 14:51:49

标签: mysql grouping date-range

我正在尝试运行一个按日期字段对联系人进行分组的查询,然后返回每个分组的计数。如果日期字段具有作为一个组的空值,如果日期字段是10年以前是另一个组,如果日期字段是3 - 10年前,那是第三个分组,并且如果日期字段是< 3年前那是最后的分组。

对此的任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

您需要在GROUP子句中使用CASE语句:

SELECT  CASE 
            WHEN floor(DATEDIFF(EndDate, StartDate)/365) < 3 THEN '<3'
            WHEN floor(DATEDIFF(EndDate, StartDate)/365) < 10 THEN '3-10'
            WHEN floor(DATEDIFF(EndDate, StartDate)/365) = 10 THEN '=10'
            ELSE '>10' 
        END AS `Length`
FROM    ...
WHERE   ...
GROUP   BY  CASE 
                WHEN floor(DATEDIFF(EndDate, StartDate)/365) < 3 THEN '<3'
                WHEN floor(DATEDIFF(EndDate, StartDate)/365) < 10 THEN '3-10'
                WHEN floor(DATEDIFF(EndDate, StartDate)/365) = 10 THEN '=10'
                ELSE '>10' 
            END
ORDER   BY Length ASC;

如果您的结束日期是现在,请使用NOW()

答案 1 :(得分:0)

http://sqlfiddle.com/#!9/86b630/2

SELECT IF(my_date IS NULL, 'NO DATE', 
          IF(YEAR(NOW())-YEAR(my_date)>10,'>10', 
            IF(YEAR(NOW())-YEAR(my_date)>3,'3-10','<3')
          )
         ) `period`, COUNT(id)
FROM contacts
GROUP BY `period`

答案 2 :(得分:0)

您可以使用子选择来准备值,然后解析它们并将它们分组:

select case 
when elapsed is null then 'missing'
when elapsed <= 1095 then 'new'
when elapsed <= 3650 then 'middle'
else 'old'
end as period, count(*)
from
(select datediff(now(), yourdate) period from yourtable) t
group by period