我有一个表,上面列出了人们的出生日期(目前是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
在尝试了许多方法后,这是100%的工作时间使用现代MS SQL格式函数,而不是转换为风格112。两者都可以,但这是最少的代码。
谁能找到一个日期组合不工作?我不认为有一个:)
--Set parameters, or choose from table.column instead:
DECLARE @DOB DATE = '2000/02/29' -- If @DOB is a leap day...
,@ToDate DATE = '2018/03/01' --...there birthday in this calculation will be
--0+ part tells SQL to calc the char(8) as numbers:
SELECT [Age] = (0+ FORMAT(@ToDate,'yyyyMMdd') - FORMAT(@DOB,'yyyyMMdd') ) /10000
我得把这个扔出去。如果您使用112样式(yyyymmdd)将日期转换为一个数字,您可以使用这样的计算…
(yyyyMMdd - yyyyMMdd) / 10000 =全年差值
declare @as_of datetime, @bday datetime;
select @as_of = '2009/10/15', @bday = '1980/4/20'
select
Convert(Char(8),@as_of,112),
Convert(Char(8),@bday,112),
0 + Convert(Char(8),@as_of,112) - Convert(Char(8),@bday,112),
(0 + Convert(Char(8),@as_of,112) - Convert(Char(8),@bday,112)) / 10000
输出
20091015 19800420 290595 29
您需要考虑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日。