I want to generate data every month for the previous month.
set (startdate, enddate) = ('2021-02-01', '2021-02-28');
Instead of manually inserting the date every month as in the above code, I want the 'startdate' variable to automatically pick the start date of previous month and the 'enddate' variable to pick the last date of previous month.
How to do that using sql?
If you want the previous month relative to the current date, you can just put it into a where
clause:
where datecol < date_trunc('month', current_date) and
datecol >= date_trunc('month', current_date) - interval '1 month'
Note that this is safer than your code, because it works when the column has a time component.
You could put this into variables. I'm not sure that is necessary.
If you wanted this as variables, you could use:
(date_trunc('month', current_date) - interval '1 month',
last_day(date_trunc('month', current_date) - interval '1 month')
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.