如何使用Postgres SQL按年份间隔选择行?

时间:2020-01-21 15:33:59

标签: sql postgresql date datetime

我有一张桌子,上面有来自卫生公共系统患者的一些数据。我在此表上有两个日期,即疾病通知的日期和患者的出生日期,例如:

notification_date | birth_date 
------------------+-----------------
 2013-02-19       | 2013-02-17
 2015-01-28       | 1984-01-22
 2015-02-08       | 1989-10-04
 2015-01-09       | 1984-05-25
 2016-01-28       | 1988-04-26
 2016-01-06       | 1986-05-20

如您所见,通过从这两列中获得年间隔,我可以找出患者在被告知疾病时的年龄。我需要询问有多少人的年龄小于4岁,而该疾病被告知。

类似的东西:

SELECT COUNT(id) 
FROM notifications 
WHERE age(notification_date, birth_date) < 4 years;

这个查询是否甚至需要一个特定的间隔?

3 个答案:

答案 0 :(得分:1)

我将使用直接日期比较:

select count(*)
from notifications n
where notification_date < birthdate  + interval '4 year';

使用age()之类的函数似乎不必要。

答案 1 :(得分:0)

尝试将DATE_PARTCount(*)

SELECT count(*) FROM notifications WHERE DATE_PART('year',age(notification_date, birth_date)) < 4;

此功能将为您提供两个日期之间的完整年。

如果需要,请在此处阅读更多信息: https://www.postgresqltutorial.com/postgresql-date_part/

答案 2 :(得分:0)

Postgres理解区间算术,因此请考虑:

SELECT count(*) 
FROM notifications 
WHERE age(notification_date, birth_date) < interval '4 years';

Demo on DB Fiddle

对于您的样本数据,只有一条满足条件的记录,因此查询将产生1