skip to Main Content

I have a column in my table with the name: efcodmov, every start of the month I need to extract all registers from the last month

end of the code:

AND efdtmov BETWEEN date('2023-01-01') AND date('2023-01-31')

How can I modify to do automatically?

3

Answers


  1. Lazy way:

    and efdtmov BETWEEN DATE_TRUNC('month',current_date-10) and DATE_TRUNC('month',current_date)-1
    

    Assumes you run within 10 days of month’s start.

    More stable, but bulkier, way:

    efdtmov BETWEEN DATE_TRUNC('month', DATE_TRUNC('month', current_date) -1) and DATE_TRUNC('month', current_date) - 1
    
    Login or Signup to reply.
  2. You can compare the year and month only as follows :

    AND date_format(efdtmov , '%Y-%m' ) = date_format ( date_add('month', -1, current_date) , '%Y-%m' )
    
    Login or Signup to reply.
  3. Use date manipulation functions, specifically date_trunc to truncate both dates to the same unit:

    where date_trunc('month', current_date) = date_trunc('month', date_add('month', -1, current_date)) 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search