Skip to content
Advertisement

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?

Advertisement

Answer

  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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement