Postgresql – SELECTing data based on a specific time frame

datepostgresqlselect

I'm using PostgreSQL. I have a table which stores data related to some orders. It has four to five columns, including:

cust_code char varying (20),
sugg_order integer,
ordered_qty integer,
date date

Now I want to find all the rows which occur within a specific time frame. Let us assume that this time frame starts on 1st of April every year and ends on 31st of March next year (like 2017-04-01 to 2018-03-31 and 2018-04-01 to 2019-03-31 and so on).

Below are the examples of the output which I want from the query:

  • If I run this query on 2018-08-01 then I need all the data from 2018-04-01 to 2018-08-01.

  • If I run this query on 2019-03-01 then I need all the data from
    2018-04-01 to 2019-03-01.

  • If I run this query on 2019-05-01 then I need all the data from 2019-04-01 to 2019-05-01

In other words, I need all data between today (the day I run the query) and the latest (most recent) 1st of April before today.

I need a query which will work for any year and I cannot get the start date of the time frame from outside.

Best Answer

I think you want something like this:

with param (date, year) as
  ( select 
        @date_param,
        extract(year from @date_param)
        - case when extract(month from @date_param) < 4 then 1 else 0 end
  )
select t.*
from table_name as t, param as p
where t.date >= make_date(p.year, 4, 1) 
  and t.date <= p.date ;