日期之间的日期顺序排序

时间:2018-09-28 03:52:02

标签: sql sql-server tsql

我有两个日期作为参数,并列出了当前日期和前几年的相同时期。我需要参数之间的分区列表。逻辑是如果日期在“ 20171201”和“ 20180301”之间,则为1,如果日期在“ 20161201”和“ 20170301”之间,则为2,依此类推。但是列表中的周期数不是静态的,例如:

DECLARE @DateEnd DATE = '20180331'
  , @DateBeg DATE = '20171201'

DECLARE @tab TABLE([date] DATE)
INSERT INTO @tab ([date])
VALUES('2014-12-01')
, ('2015-01-01')
, ('2015-02-01')
, ('2015-03-01')
, ('2015-12-01')
, ('2016-01-01')
, ('2016-02-01')
, ('2016-03-01')
, ('2016-12-01')
, ('2017-01-01')
, ('2017-02-01')
, ('2017-03-01')
, ('2017-12-01')
, ('2018-01-01')
, ('2018-02-01')
, ('2018-03-01')

结果应该是

Date        Cnt
2014-12-01  4
2015-01-01  4
2015-02-01  4
2015-03-01  4
2015-12-01  3
2016-01-01  3
2016-02-01  3
2016-03-01  3
2016-12-01  2
2017-01-01  2
2017-02-01  2
2017-03-01  2
2017-12-01  1
2018-01-01  1
2018-02-01  1
2018-03-01  1

2 个答案:

答案 0 :(得分:2)

使用CASE WHEN来检查日期并相应地返回值

select  *, 
        Cnt = CASE 
              WHEN date BETWEEN '20171201' AND '20180331' THEN 1
              WHEN date BETWEEN '20161201' AND '20170331' THEN 2            
              WHEN date BETWEEN '20151201' AND '20160331' THEN 3
              WHEN date BETWEEN '20141201' AND '20150331' THEN 4            
              END
from    @tab

编辑:

或者这就是您想要的?

这将为您提供财政年度的开始

dateadd(month, - month(date) % 12, date)

您的Cnt是财政年度到今天之间的年份吗?

select  *, 
        Cnt = datediff(year, dateadd(month, - month(date) % 12, date), getdate())
from    @tab

答案 1 :(得分:0)

在案例表达式中使用dateadd()应该启用此功能:

select
  datecol
, case when datecol between @DateBeg and @DateEnd then 1 
       when datecol between dateadd(year,-1,@DateBeg) and dateadd(year,-1,@DateEnd) then 2
       when datecol between dateadd(year,-2,@DateBeg) and dateadd(year,-2,@DateEnd) then 3
       when datecol between dateadd(year,-3,@DateBeg) and dateadd(year,-3,@DateEnd) then 4
  end
from @tab

另请参阅:http://rextester.com/BTF82190