2016-09-30 329 views
2

我有日期,从1960年开始至2016年的名单我想借此月份和日期的日和:SQL日期部分增加一年

- If Month and Day > Today then add 2016 as Yr BUT 
    - If Month and Day < Today then add 2017 as Yr 

这里是SQL我到目前为止:

Select DATEPART(MM, Date) as Month, 
    DATEPART(dd, Date) as DayNum 
    From DateTable 
    WHERE CategoryID = 3 
+0

你能证明你怎么样输出看起来像? –

回答

1

事情是这样的:

select (case when month(date) * 100 + day(date) < month(getdate()) * 100 + day(getdate()) 
      then datefromparts(2017, month(date), day(date) 
      else datefromparts(2016, month(date), day(date) 
     end) as next_anniversary 
from datetable 
where categoryid = 3; 

你实际上并不需要做算术。这相当于:

select (case when month(date) < month(getdate()) or 
        month(date) = month(getdate()) and day(date) < day(getdate()) 
      then datefromparts(2017, month(date), day(date) 
      else datefromparts(2016, month(date), day(date) 
     end) as next_anniversary 
from datetable 
where categoryid = 3; 

另外,datefromparts()在SQL Server 2012+中可用。您可以在早期版本的SQL Server中拼凑类似的功能,但这更简单。

0

这是一个简单的方法来做到这一点。工程就好了

SELECT CASE WHEN SUBSTRING(CAST(CAST(Date AS DATE) AS NVARCHAR),6,10)<SUBSTRING(CAST(CAST(GETDATE() AS DATE) AS NVARCHAR),6,10) 
THEN datefromparts(2017, month(Date), day(Date)) 
ELSE datefromparts(2016, month(Date), day(Date)) END 
FROM datetable 
WHERE categoryid = 3; 

让我知道它是否也适用于你。

柜面您正在运行SQL Server 2008,DATEFROMPARTS将无法​​正常工作,而不是使用

SELECT CASE WHEN SUBSTRING(CAST(CAST(Date AS DATE) AS NVARCHAR),6,10)<SUBSTRING(CAST(CAST(GETDATE() AS DATE) AS NVARCHAR),6,10) 
THEN DATEADD(YEAR, 2017-YEAR(ex_date), Date) 
ELSE DATEADD(YEAR, 2016-YEAR(ex_date), Date) 
END 
FROM datetable 
WHERE categoryid = 3; 
0

使用SQL Server版本以下查询从2008年

 SELECT CASE WHEN month(date) < =month(getdate()) and day(date) < day(getdate()) 
        THEN CONVERT(DATE,'2017-'+ 
           CAST(Month(date) AS VARCHAR(2))+'-'+CAST(Day(date) AS VARCHAR(2))) 
        ELSE CONVERT(DATE,'2016-'+ 
          CAST(Month(date) AS VARCHAR(2))+'-'+CAST(Day(date) AS VARCHAR(2))) END as new_date 
    FROM datetable 
    WHERE categoryid = 3;