简体   繁体   中英

SQL Find Age using DateDiff


Fields        || Data

ID            || V465

DOB           || 1946-09-05

DATE_OF_DEATH || 1974-05-11

I am using this SQL but I am getting an error.

select DATEDIFF("YYYY",'DOB','DATE_OF_DEATH') where ID= 'V465'

Its SQL SERVER Management Studio R2 and

Error: Msg 207, Level 16, State 1, Line 2 Invalid column name 'ID'

You forgot the FROM (and surrounded your column names with single quotes which treats them as string literals):

select DATEDIFF("YYYY",DOB,DATE_OF_DEATH) 
FROM {tablename}
where ID= 'V465'

And DATEDIFF alone is not the right way to determine "age" since

DATEDIFF("yyyy",'2001-12-01','2003-01-31')

will give you 2 instead of 1 .

See one method here and another here

that error most likely comes from not including a table in your select statement

select DATEDIFF(YY,DOB,DATE_OF_DEATH) AS AGE
  FROM TABLE_NAME 
 where ID= 'V465'
SELECT DATEDIFF(YY,'01-01-2001','12-31-2002')

在MSSQL上返回1

Test Data

DECLARE @TABLE TABLE(ID  VARCHAR(20),DOB DATE, DATE_OF_DEATH DATE)
INSERT INTO @TABLE VALUES
('V465', '1946-09-05', '1974-05-11'),('V466', '1945-09-05', '2000-11-11'),
('V467', '1982-09-05', NULL),('V468', '1946-09-05', NULL)

Query

SELECT DATEDIFF(YEAR,DOB, COALESCE(DATE_OF_DEATH, GETDATE())) AS AGE
FROM @TABLE

Using COALESCE function if someone hasnt died yet you can calculate their age too. COALESCE function will take difference from date of death and if the column is null it will take difference from today's date. and will give you the following result.

Result

╔═════╗
║ AGE ║
╠═════╣
║  28 ║
║  55 ║
║  32 ║
║  68 ║
╚═════╝

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM