postgre如何从过去 x 个月获取数据 Postgres SQL 查询,其中日期字段是时间戳?



我正在尝试编写一个sql查询,我可以在其中获取过去3个月的数据。具体来说,我想看看每个客户在过去 3 个月内花了多少钱。我的日期字段是带有时区的时间戳(例如,2017-07-14 00:56:43.833191+00"(。

我不是在尝试获取过去 90 天的数据,而是实际上获取过去 3 个月的数据,因此如果当前是 2017 年 7 月 14 日,我想获取 2017 年 4 月 1 日至 2017 年 6 月 30 日之间的数据。

这是我目前拥有的,如果 3 个月在同一年,它的效果很好,但它不能跨年工作,这意味着如果当前日期是 2017 年 2 月 15 日,我希望它返回从 2016 年 11 月 1 日到 2017 年 1 月 31 日的数据。 但是,这行不通。

这是我当前的查询。 我将不胜感激任何帮助。 谢谢!

select sum(amount), customer_id
from payments
where (date_part('month',payment_date) < (date_part('month',current_timestamp)-1) and
date_part('month',payment_date) >=  (date_part('month',current_timestamp)-3) ) and 
(date_part('year',date_created) = date_part('year',current_timestamp))
group by customer_id

嗯。 . .我认为date_trunc()要简单得多:

select sum(amount), customer_id
from payments
where payment_date >= date_trunc('month', now()) - interval '3 month' and
payment_date < date_trunc('month', now())
group by customer_id;

最新更新