Abhilash Singh Chauhan
Abhilash Singh Chauhan

Reputation: 289

How to add/subtract n number of days from a custom date in postgresql?

I have a database in which, I have a issue_date column, and forecast_date column,

database

I am selecting the maximum date from the database,

but I want to fetch/query/extract the N th previous day from maximum available date

like (maximum date - 1 / 2 or n number of days).

SELECT issue_date, forecast_date, state_name, district_name, rainfall, geometry 
FROM all_parameters_forecast_data 
WHERE "forecast_date" = (SELECT ((MAX("forecast_date")- INTERVAL '1 day') AS "forecast_date") FROM all_parameters_forecast_data)

& As the max date is custom,

so can not use today or yesterday logic here. Is there any way possible?

Upvotes: 0

Views: 84

Answers (1)

S-Man
S-Man

Reputation: 23676

  1. Calculate the MAX date
  2. Filter your records using BETWEEN max_date - n AND max_date

Example:

SELECT issue_date, forecast_date, state_name, district_name, rainfall, geometry 
FROM (
    SELECT
        *,
        MAX("forecast_data") OVER () as max_forecast_date
    FROM 
        all_parameters_forecast_data
) s
WHERE "forecast_date" BETWEEN max_forecast_date - n AND max_forecast_date

There are many ways to achieve #1. In my example I used the MAX() window function to add the required value as separate column which can be used for comparison later.

Upvotes: 1

Related Questions