简体   繁体   English

SQL使用DateDiff查找年龄

[英]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. 我正在使用此SQL,但出现错误。

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

Its SQL SERVER Management Studio R2 and 其SQL SERVER Management Studio R2和

Error: Msg 207, Level 16, State 1, Line 2 Invalid column name 'ID' 错误:消息207,级别16,状态1,第2行无效的列名称'ID'

You forgot the FROM (and surrounded your column names with single quotes which treats them as string literals): 您忘记了FROM (并且您的列名用单引号引起来,将其视为字符串文字):

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并不是确定“年龄”的正确方法,因为

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

will give you 2 instead of 1 . 将给您2而不是1

See one method here and another here 见一个方法在这里和其他在这里

that error most likely comes from not including a table in your select statement 该错误最有可能来自您的select语句中未包含表

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函数,您也可以计算他们的年龄。 COALESCE function will take difference from date of death and if the column is null it will take difference from today's date. COALESCE函数将与死亡日期发生差异,并且如果该列为空,它将与今天的日期发生差异。 and will give you the following result. 并会给您以下结果。

Result 结果

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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