简体   繁体   中英

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,

数据库

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?

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM