Home > database >  Date range in window functions PostgreSQL
Date range in window functions PostgreSQL

Time:01-19

I have a table with data for the whole of 2021 and 2022. I need to calculate the cumulative amount of the field by date for the previous year. For example, the row with date 2022-03-01 must have the value of the cumulative amount for 2021-03-01

I am trying this window function:

SUM(fact_mln) OVER(PARTITION BY date - INTERVAL '1 year' ORDER BY date)

But the method - INTERVAl '1 year' is not working

How can this window function be converted or is there any other solution?

CodePudding user response:

You don't need PARTITION BY:

CREATE TABLE laurenz.amounts (
    id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    date date NOT NULL,
    fact_mln double precision NOT NULL
);

INSERT INTO amounts (date, fact_mln) VALUES
    ('2021-03-01', 1),
    ('2021-03-01', 2),
    ('2021-03-02', 3),
    ('2021-03-02', 4),
    ('2021-03-03', 5),
    ('2022-02-28', 6),
    ('2022-03-01', 7),
    ('2022-03-01', 8),
    ('2022-03-02', 9);

SELECT date, fact_mln,
       sum(fact_mln) OVER (ORDER BY date
                           RANGE BETWEEN INTERVAL '1' YEAR PRECEDING
                                     AND INTERVAL '1' YEAR PRECEDING)
FROM amounts;

    date    │ fact_mln │ sum 
════════════╪══════════╪═════
 2021-03-01 │        1 │   ∅
 2021-03-01 │        2 │   ∅
 2021-03-02 │        3 │   ∅
 2021-03-02 │        4 │   ∅
 2021-03-03 │        5 │   ∅
 2022-02-28 │        6 │   ∅
 2022-03-01 │        7 │   3
 2022-03-01 │        8 │   3
 2022-03-02 │        9 │   7
(9 rows)
  • Related