使用postgresql计算datediff并得出年数

时间:2019-04-01 09:18:34

标签: sql postgresql datetime

我有两个输入日期值,想计算这些日期之间的差(无年数)并将其存储为年龄

我尝试使用下面的psql命令。但是,结果为十进制形式。我该如何取整呢,还有其他优雅的方法可以写吗?

select icu.intime, p.dob, EXTRACT('epoch' from icu.intime - p.dob) / 60.0 / 
60.0 / 24.0 / 365.242 as age from patients p inner join 
icustays icu on p.subject_id = icu.subject_id

尽管我获得了年龄值,但我想将其四舍五入。enter image description here

1 个答案:

答案 0 :(得分:1)

使用年龄功能

select age(intime,dob)

所以您的情况应该是

select icu.intime, p.dob, age(icu.intime,p.dob) as number_age from patients p inner join 
icustays icu on p.subject_id = icu.subject_id

如果只需要Yeara,请使用提取年份

EXTRACT(YEAR from (age(icu.intime,p.dob)))