同一列上的日期差异

时间:2017-08-09 10:56:01

标签: sql

我有一张带有ID和datelastupdated列的表,我需要计算12,24,36个月的日期差异

ID    Datelastupdate
1012    1/1/2016
1012    1/2/2017
1012    1/7/2014
2014    1/1/2015
2014    1/1/2016
3071    2/2/2017
3071    2/2/2015

输出:

 Count  Monthsdiff
    1   12
    1   24
    1   >24

1 个答案:

答案 0 :(得分:0)

您可以使用两个级别的聚合来执行此操作。使用ANSI SQL日期函数:

select which, count(*)
from (select id,
             (case when max(Datelastupdate) <= min(Datelastupdate) + interval '12 month'
                   then '12'
                   when max(Datelastupdate) <= min(Datelastupdate) + interval '24 month'
                   then '24'
                   when max(Datelastupdate) <= min(Datelastupdate) + interval '12 month'
                   else '24+'
              end) as which
      from t
      group by id
     ) t
group by which;