我正在寻求一些帮助:
我需要计算截至 2020 年 2 月 1 日的会员年龄(DoB 字段)。例如,如果成员的 DoB 为 2/18/91,我希望看到两个字段。 1 为会员截至今日的实际年龄,然后为截至 2020 年 2 月 1 日的会员年龄。在此示例中,第一个字段中的年龄应为 30,但第二个字段中的年龄应为 29。
我尝试使用一些 datefiff 和 datepart,但我似乎无法得到它。我正在使用 SSMS 2016。
你的计算是错误的。那个人当时应该28岁了。
一个简单的技巧是将日期视为 yyyyMMdd 形式的数字,然后用 DOB 减去目标日期并得到整数部分。与您的样本日期:
DECLARE @dob DATETIME='19910218';
DECLARE @targets TABLE(target DATETIME);
INSERT @targets(target)VALUES('20200201'), (GETDATE());
SELECT
FLOOR(((YEAR(target)* 10000+MONTH(target)* 100+DAY(target))
-(YEAR(@dob)* 10000+MONTH(@dob)* 100+DAY(@dob))
)/ 10000
)
FROM @targets;
PS:下限可能是不必要的,SQL Server 进行整数除法,但我想保留它以确保安全。
将日期转换为 8 个字符的整数,减去并除以 10000:
declare @Birthdate date = '2/18/91'
declare @AsOfDate date = '2/1/2020'
select (0+convert(char(8),getdate(),112) - convert(char(8),@birthdate,112)) / 10000 as CurrentAge
, (0+convert(char(8),@asofdate,112) - convert(char(8),@birthdate,112)) / 10000 as FebAge
datediff(year, <birthdate>, <currentdate>) +
case when
month(<birthdate>) > month(<currentdate>) or
month(<birthdate>) = month(<currentdate>) and
day(<birthdate>) > day(<currentdate>)
then -1 else 0 end