表1
ID Dateofbirth
001 01/01/1988 'dd/mm/yyyy
002 01/05/2001
....
从表1中,我想找到每个id的最近生日。最近的生日应该使用系统日期进行验证。
预期输出
ID Dateofbirth MostRecentBirthday
001 01/01/1988 01/01/2012
002 01/05/2001 01/05/2011
....
输出说明
For 001, most recent birthday is 01/01/2012
For 002, most recent birthday is 01/05/2011 ' because still we are not reached this date 01/05/2012
答案 0 :(得分:3)
与上一个问题的答案类似:
select ID,
Dateofbirth,
dateadd(yy,
datediff(yy,Dateofbirth,getdate()) -
case when dateadd(yy,datediff(yy,Dateofbirth,getdate()),Dateofbirth)>getdate()
then 1 else 0 end,
Dateofbirth) MostRecentBirthday
from ...
答案 1 :(得分:0)
假设列类型为DATE
(或DATETIME
):
SELECT id,
Dateofbirth,
CONVERT(date,
DATEPART(month, Dateofbirth) + '/'
+ DATEPART(day, Dateofbirth) + '/'
+ CASE WHEN DATEPART(month, Dateofbirth) < DATEPART(month, GETDATE()) OR
(DATEPART(month, Dateofbirth) = DATEPART(month, GETDATE()) AND DATEPART(day, Dateofbirth) < DATEPART(day, GETDATE()))
THEN DATEPART(year, GETDATE())
ELSE DATEPART(year, GETDATE())-1
END,
101) AS MostRecentBirthday
FROM your_table
未经测试,但应该非常接近。
答案 2 :(得分:0)
如果您使用Age UDF,则查询可以只是:
SELECT
ID,
Dateofbirth,
DATEADD(year, dbo.Age(Dateofbirth), Dateofbirth) AS MostRecentBirthday
FROM
...
答案 3 :(得分:0)
这个想法可能有所帮助
SELECT
ID,
dateofbirth,
convert(nvarchar(10), day(dateofbirth)) + "/" +
convert(nvarchar(10), month(dateofbirth)) +
CASE month(getdate()) > Month(dateofbirth)
WHEN TRUE THEN convert(nvarchar(10), year(getdate()))
ELSE CASE month(getdate()) < Month(dateofbirth)
WHEN TRUE THEN convert(nvarchar(10), Year(getdate())-1)
ELSE CASE day(getdate()) >= day(dateofbirth)
WHEN TRUE THEN Year(getdate())
ELSE Year(getdate())-1)
END
END
END MostRecentBirthday
FROM .....