简体   繁体   中英

Dynamically extract data for previous month

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')
)

Is this what you're after?

select 
     current_date()                         today 
   , date_trunc(month,add_months(today,-1)) first_day_last_month 
   , last_day ( first_day_last_month)       last_day_last_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM