我有一个从1960年到2016年的日期列表。我想采取日期的月份和日期:
- 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中拼凑相似的功能,但这更简单。
答案 1 :(得分: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;
答案 2 :(得分:0)
对2008年的SQL Server版本使用以下查询。
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;