我正在努力让所有生日即将到来的员工,似乎我想要去的东西不能正常运作,因为每年都在考虑这一年。
所以我现在的查询是
SELECT [emp].[FirstName]
,[emp].[LastName]
,[emp].[Birthday]
FROM [Employees] AS [emp]
WHERE [emp].[ID] != 12
AND [emp].[Birthday] >= GETDATE()
AND [emp].[Birthday] <= DATEADD(dd,20,GETDATE())
问题是2016年没有员工生日。任何想法我怎么能检查这个
答案 0 :(得分:1)
SELECT [emp].[FirstName]
,[emp].[LastName]
,[emp].[Birthday]
FROM [Employees] AS [emp]
WHERE [emp].[ID] != 12
AND MONTH([emp].[Birthday]) IN (MONTH(GETDATE()),MONTH(DATEADD(MONTH,1,GETDATE())))
AND DAY([emp].[Birthday]) >= DAY(GETDATE())
<强>更新强>
我没有意识到这可能会变得如此复杂,如果数字中的当前日期大于数字中的生日日期,则上述查询将不起作用(例如:如果当前日期为29且生日为下个月的3日) )
我尝试使用更新版本,到目前为止效果很好。
SELECT [emp].[FirstName]
,[emp].[LastName]
,[emp].[Birthday]
FROM [Employees] AS [emp]
WHERE [emp].[ID] != 12
AND ((MONTH([emp].[Birthday]) = MONTH(GETDATE()) AND DAY([emp].[Birthday]) > DAY(GETDATE()))
OR (MONTH([emp].[Birthday]) = MONTH(DATEADD(MONTH,1,GETDATE())) AND DAY([emp].[Birthday]) < DAY(DATEADD(MONTH,1,GETDATE()))))
所以,逻辑是:
If
生日月份为same
当月,则日期应为greater
,而不是当前日期
如果生日月份是current+1
个月,那么日期应该是lesser
而不是下个月的日期。
答案 1 :(得分:1)
如果您使用的是SQL Server 2012或更高版本,则可以使用DATEFROMPARTS
功能将您的生日日期强制转换为当前年份:
SELECT [emp].[FirstName]
,[emp].[LastName]
,[emp].[Birthday]
FROM [Employees] AS [emp]
WHERE [emp].[ID] != 12
AND CASE
WHEN DATEPART(MONTH, Birthday) = 2 AND DATEPART(DAY, Birthday) = 29
THEN DATEFROMPARTS(DATEPART(YEAR, GETDATE()), 3, 1)
ELSE
DATEFROMPARTS(DATEPART(YEAR, GETDATE())+1, DATEPART(MONTH, Birthday), DATEPART(DAY, Birthday)) END
BETWEEN GETDATE() AND DATEADD(DAY, 30, GETDATE())
答案 2 :(得分:1)
更简单,更清洁:
WHERE [emp].[ID] != 12
AND DATEPART(dayofyear, [emp].[Birthday]) BETWEEN DATEPART(dayofyear, GETDATE()) AND DATEPART(dayofyear, GETDATE() + 30)
答案 3 :(得分:0)
这可能更漂亮,但是今天接近年底并且在明年年初有生日时,它不会挂断:
SELECT [emp].[FirstName]
,[emp].[LastName]
,[emp].[Birthday]
FROM [Employees] AS [emp]
WHERE [emp].[ID] != 12
AND DATEDIFF(dd, GETDATE(), DATEADD(yy, CASE WHEN DATEADD(yy, DATEDIFF(yy, [emp].Birthday, GETDATE()), [emp].Birthday) < DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0) THEN 1 ELSE 0 END + DATEDIFF(yy, [emp].Birthday, GETDATE()), [emp].Birthday)) BETWEEN 0 AND 20