postgresql - 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')
这个答案的问题
- 如果从现在起 30 天后是明年,这将不起作用。
- 如果年份是闰年,这个间隔不需要是 31 天吗?
解决方案
我根据当前年份和用户的生日月份和日期生成了一个新日期,然后查看是否在接下来的 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)
推荐阅读
- r - 如何编号唯一对 X,Y
- c# - 在 Xamarin C# Visual Studio 中创建 TableView
- javascript - 如何使用javascript集成字符串中字符的计数频率
- c# - 始终使用最新版本的 Newtonsoft.Json
- c# - 无法首先在列实体框架代码上定义 PRIMARY KEY 约束
- emacs - 使用估计在 emacs org-mode 中自动安排待办事项
- r - Safari 浏览器上的 Shinyapps.io 无法连接到服务器“localhost”
- python-3.x - cv2.HoughCircles 需要超过 15 分钟才能运行
- javascript - 路由时AngularJs memoryLeak
- javascript - 如何使用firebase函数从文档中查询一个数字并将其全部汇总到firestore中的父文档中