I am trying to create a materialized-view in postgres, where I sum 2 columns, depending on todays date within a window function.
In the below picture there is an example of the query I am trying to achieve:
If today is the ‘2022-06-06’:
- 2022-06-05: 1+2+3+4+5
- 2022-06-06: 1+2+3+4+5+6+107
- 2022-06-07: 1+2+3+4+5+6+107+108
Here is a sample fiddle with date:
http://sqlfiddle.com/#!15/538ea7/1 Updated: http://sqlfiddle.com/#!15/bef30/3
Would greatly appreciate any help!
Old Image:
Edit: Updated Fiddle and Image
Advertisement
Answer
If I understood you correctly, you need the following result
user_id | date | actual | scheduled | sum ------: | :--------- | -----: | --------: | --: 1 | 2022-06-01 | 1 | 100 | 1 1 | 2022-06-02 | 2 | 101 | 3 1 | 2022-06-03 | 3 | 103 | 6 1 | 2022-06-04 | 4 | 104 | 10 1 | 2022-06-05 | 5 | 105 | 15 2 | 2022-06-06 | 6 | 106 | 21 2 | 2022-06-07 | 7 | 107 | 128 2 | 2022-06-08 | 8 | 108 | 236 2 | 2022-06-09 | 9 | 109 | 345 2 | 2022-06-10 | 10 | 110 | 455
Then you can use a query like this
SELECT user_id, date, actual, scheduled, SUM(CASE WHEN date <= '2022-06-6' THEN actual ELSE scheduled END) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM table_1
Working demo