首页 > 解决方案 > Postgres:是从现在到每个生日的间隔的日期

问题描述

我希望能够返回从现在到指定时间间隔过生日的用户。

用户模型

我的时间间隔= 30 天

我的数据集

|---------------------|------------------|------------------|
|      id             |     name         |     birthday     |
|---------------------|------------------|------------------|
|          1          |        Tim       |   27/06/1994     |
|---------------------|------------------|------------------|

我的尝试

SELECT * FROM User where User.birthday BETWEEN NOW()::timestamp AND to_char(NOW() + interval '30 days','MM-DD')::timestamp;

退货

空的。Postgres 假设通过省略年份我实际上是指第 1 年。

我想要的是

此查询返回所有生日在该区间内的用户,无论年份如何。

尝试从答案(非常感谢@Mureinik)

SELECT *
FROM   user
WHERE  birthday BETWEEN TO_CHAR(NOW(), 'MM-DD') AND
TO_CHAR(NOW() + INTERVAL '30 days','MM-DD')

这个答案的问题

标签: postgresqlpostgresql-9.6

解决方案


我根据当前年份和用户的生日月份和日期生成了一个新日期,然后查看是否在接下来的 30 天内。

select *
from user
where date(date_part('year', current_date)||'-'||date_part('month', birthday)||'-'||date_part('day', birthday))
    between current_date and current_date + interval '30 days';

例如:

# select * from user;
 id | name  |  birthday
----+-------+------------
  1 | Tim   | 1994-06-27
  2 | Steve | 1982-06-23
  3 | Dave  | 1980-07-29
(3 rows)

# select *
from user
where date(date_part('year', current_date)||'-'||date_part('month', birthday)||'-'||date_part('day', birthday))
    between current_date and current_date + interval '30 days';
 id | name  |  birthday
----+-------+------------
  1 | Tim   | 1994-06-27
  2 | Steve | 1982-06-23
(2 rows)

推荐阅读