问题
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