2016-09-30 68 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;