我有一个表,上面列出了人们的出生日期(目前是nvarchar(25))
我如何将其转换为日期,然后以年为单位计算他们的年龄?
我的数据如下所示
ID Name DOB
1 John 1992-01-09 00:00:00
2 Sally 1959-05-20 00:00:00
我希望看到:
ID Name AGE DOB
1 John 17 1992-01-09 00:00:00
2 Sally 50 1959-05-20 00:00:00
您需要考虑datediff命令的查房方式。
SELECT CASE WHEN dateadd(year, datediff (year, DOB, getdate()), DOB) > getdate()
THEN datediff(year, DOB, getdate()) - 1
ELSE datediff(year, DOB, getdate())
END as Age
FROM <table>
我从这里改编的。
请注意,对于非闰年,将把2月28日视为闰年的生日,例如,2020年2月29日出生的人将被视为2021年2月28日的1岁生日,而不是2021年3月1日。
declare @birthday as datetime
set @birthday = '2000-01-01'
declare @today as datetime
set @today = GetDate()
select
case when ( substring(convert(varchar, @today, 112), 5,4) >= substring(convert(varchar, @birthday, 112), 5,4) ) then
(datepart(year,@today) - datepart(year,@birthday))
else
(datepart(year,@today) - datepart(year,@birthday)) - 1
end
标记为正确的答案更接近准确,但在以下情况下,它失败了——出生年份是闰年,日在二月之后
declare @ReportStartDate datetime = CONVERT(datetime, '1/1/2014'),
@DateofBirth datetime = CONVERT(datetime, '2/29/1948')
FLOOR(DATEDIFF(HOUR,@DateofBirth,@ReportStartDate )/8766)
OR
FLOOR(DATEDIFF(HOUR,@DateofBirth,@ReportStartDate )/8765.82) -- Divisor is more accurate than 8766
下面的解决方案给了我更准确的结果。
FLOOR(DATEDIFF(YEAR,@DateofBirth,@ReportStartDate) - (CASE WHEN DATEADD(YY,DATEDIFF(YEAR,@DateofBirth,@ReportStartDate),@DateofBirth) > @ReportStartDate THEN 1 ELSE 0 END ))
它几乎适用于所有场景,包括闰年、2月29日等。
如果这个公式有漏洞,请指正。