how to get dates with postgres

落爺英雄遲暮 提交于 2021-01-28 08:08:44

问题


I was trying to query and return the sum of all records in the last 4 past weeks. I had it working however I while using timestamps. and I am trying to change the precision and and just use dates.

briefly instead of timestamp ranges I want just date ranges.

this what I had with timestamps.

with date_ranges (range_name, range_dates) as
              ( values ('week_0', tstzrange ((now()-interval '6 days'),  now(),'[]'))
                      , ('week_1', tstzrange ((now()-interval '13 days'), (now()-interval '7 days'), '[]'))
                      , ('week_2', tstzrange ((now()-interval '20 days'), (now()-interval '14 days'),'[]'))
                      , ('week_3', tstzrange ((now()-interval '27 days'), (now()-interval '21 days'),'[]')) 
              ) 
  select range_name, range_dates, sum("transactionTotal") total_amount 
  from "MoneyTransactions" mt
  join date_ranges dr on (mt."createdAt" <@ range_dates)
  group by range_name, range_dates
  order by range_name;

I tried changing tstzrange with daterange but I get the following error

function daterange(timestamp with time zone, timestamp with time zone, unknown) does not exist

I don't have that much background with SQL so an small explanation is much appreciated.


回答1:


You would simply cast to date. However, be careful when you do that. You should use multiples of 7 along exclusive (default upper bounds). Thus it looks like:

with date_ranges (range_name, range_dates) as
              ( values ('week_0', tstzrange ((now()::date-interval '7 days'),  now()::date))
                      , ('week_1', tstzrange ((now()::date-interval '14 days'), (now()::date-interval '7 days')))
                      , ('week_2', tstzrange ((now()::date-interval '21 days'), (now()::date-interval '14 days')))
                      , ('week_3', tstzrange ((now()::date-interval '28 days'), (now()::date-interval '21 days')))
              )
          select range_name, range_dates, sum("transactionTotal") total_amount 
  from "MoneyTransactions" mt
  join date_ranges dr on (mt."createdAt" <@ range_dates)
  group by range_name, range_dates
  order by range_name;


来源:https://stackoverflow.com/questions/63813222/how-to-get-dates-with-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!