【问题标题】:Fetch records of current month using PostgreSQL query使用 PostgreSQL 查询获取当月记录
【发布时间】:2021-06-21 12:05:03
【问题描述】:
假设我在表格中有以下数据
id createdAt
1 2021-02-26T06:29:03.482Z
2 2021-02-27T06:29:03.482Z
3 2021-03-14T06:29:03.482Z
4 2021-03-17T06:29:03.482Z
我想要当前月份的数据。即,如果我在 3 月份生成报告,我需要获取 3 月份的结果,因此我们只需要表中的当前月份数据。
想要的输出是
id createdAt
3 2021-03-14T06:29:03.482Z
4 2021-03-17T06:29:03.482Z
请大家帮忙。谢谢。
【问题讨论】:
标签:
postgresql
date-arithmetic
【解决方案1】:
您可以将日期的月份和年份与当前日期进行比较。但是不会使用按字段的索引,您可以为此建立一个单独的按年和月的索引。
select *
from your_table
where extract(YEAR FROM createdAt) = extract(YEAR FROM now())
and extract(MONTH FROM createdAt) = extract(MONTH FROM now())
【解决方案2】:
你可以使用date_trunc():
select *
from the_table
where date_trunc('month', createdat) = date_trunc('month', current_timestamp);
date_trunc('month', ...) 返回该月的第一天。
但是,以上内容无法使用createdat 上的索引。要提高性能,请使用范围查询:
select *
from the_table
where createdat >= date_trunc('month', current_timestamp)
and createdat < date_trunc('month', current_timestamp) + interval '1 month'
表达式date_trunc('month', current_timestamp) + interval '1 month'返回下一个月的开始(这就是与<比较的方式)