skip to Main Content

I am trying to add a date range to my sql query.
The date range should change every quarter
Example on April 1 2024 – The date range for the data should be trailing 12 months, ie it should look at 01 April 2023 to 30 March 2024 data.

This date range of (01 April 2023 to 30 March 2024) should remain constant until the quarter finishes i.e. up to 01 July 2024.
On 01 July 2024 the date range should automatically update to (01 July 2023 to 30 June 2024).

I do not want to hardcode these dates in the query, can this be automated ?

2

Answers


  1. Please try this query to get expected result. This is the PostgreSQL query. select date(date_trunc(‘quarter’, CURRENT_DATE – INTERVAL ‘1 year’ )) as start_date , date(date_trunc(‘quarter’, CURRENT_DATE ) – interval ‘1 day’) as end_date;

    Login or Signup to reply.
  2. Just apply the date functions available in your DBMS. E.g.:

    select *
    from mytable
    where mydate < date_trunc('quarter', current_date)
      and mydate >= add_months(date_trunc('quarter', current_date), -13)
    order by mydate;
    

    Docs:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search