我有一个出生日期列,我需要比较当前的日期,并返回差异的年龄。目前,我正在使用以下查询:
DECLARE @DateOfBirth date = '2000-07-27'
DECLARE @CurrentDate date = '2015-07-25'
SELECT
@Age = DATEDIFF(YEAR, @DateOfBirth, @CurrentDate)我得到了15的差异,但预期的结果应该是14,这是因为它比较了年份,得到了2015年和2000年之间的差异。因此,我使用了以下查询:
select
@Age = CAST(datediff(day, @DOB, @CurrentDate) / 365.2425 AS INT)
RESULT : 14但是当我把出生日期改为'2000-07-25‘时,我仍然得到了14的数值,但应该是15,因为日期差正好是15年。
我怎么才能得到确切的年份差异呢?
发布于 2015-07-25 08:08:38
用YYYYMMDD格式互相减去一个,然后用整数除法除以10000 (整数除法)。
所以:
(YEAR(@CurrentDate) * 10000 + MONTH(@CurrentDate) * 100 + DAY(@CurrentDate)
- YEAR(@DateOfBirth) * 10000 - MONTH(@DateOfBirth) * 100 - DAY(@DateOfBirth)
) / 1000020150725-20000727 = 149998,149998 / 10000 = 14
您也可以使用CONVERT(int,CONVERT(char(8),@CurrentDate,112)),因为样式112是YYYYMMDD,但在我看来,这有点模糊。
发布于 2022-12-02 16:09:37
我采用了Robs方法,并将其转换为函数,并为其编写了测试脚本。我再也找不到任何错误了。
CREATE or alter FUNCTION dbo.CalcAge
(
@DOB date, /* birthday */
@Today date /* either today or the day you want to calculate the age for */
)
RETURNS TABLE
AS
RETURN
(
-- from https://dba.stackexchange.com/questions/108078/how-to-get-exact-year-difference-between-two-dates-in-sql-server/108079#108079
select (YEAR(@Today) * 10000 + MONTH(@Today) * 100 + DAY(@Today)
- YEAR(@DOB) * 10000 - MONTH(@DOB) * 100 - DAY(@DOB)
) / 10000 as Age
)
go
drop table if exists #h
create table #h (dob date, now date, years int, months int, days int)
-- dob now years months days
insert into #h
values
('2012-02-29', '2013-02-28', 0, 11, 30)
, ('2012-02-29', '2013-03-01', 1, 0, 0)
, ('2012-02-29', '2016-02-28', 3, 11, 30)
, ('2012-02-29', '2016-02-29', 4, 0, 0)
, ('2012-02-29', '2016-03-31', 4, 1, 2)
, ('2012-01-30', '2016-02-29', 4, 0, 30)
, ('2012-01-30', '2016-03-01', 4, 1, 2)
, ('2011-12-30', '2016-02-29', 4, 1, 30)
, ('1822-11-04', '2022-11-04',200, 0, 0)
, ('2000-02-29', '2004-02-28', 3, 11, 30)
, ('1900-02-28', '2000-02-29',100, 0, 0)
, ('1900-02-28', '2001-02-28',101, 0, 0)
, ('2000-02-28', '2104-02-28',104, 0, 0)
, ('2000-02-29', '2104-02-29',104, 0, 0)
, ('2012-03-28', '2017-03-28', 5, 0, 0)
, ('2012-03-28', '2017-03-29', 5, 0, 0)
select *
from #h h
cross apply dbo.CalcAge (dob, now) as A
--where h.years <> a.Age
order by h.dob, h.now
go
drop function if exists dbo.CalcAgehttps://dba.stackexchange.com/questions/108078
复制相似问题