Is there a way to run a window function where the partition is for a date column and I need the the values to be aggregated in a weekly interval.
For example in this dataset
Date | Value |
---|---|
01-01-2022 | 10 |
02-01-2022 | 15 |
10-01-2022 | 01 |
11-01-2022 | 12 |
20-01-2022 | 09 |
25-01-2022 | 08 |
I want a window function to calculate the average of the value column for the first week (starting 01-01-2022) of 2022, and the subsequent weeks.
Currently creating a new column with the week number for each entry and partitioning on that new column is the only way I can think of solving this. Is there a more elegant way that I’m not familiar with within the window functions in Postgres.
2
Answers
Something like this?
Usually I don’t use WW, but IW the ISO week numbering. But that’s up to you.
Using PG14+ date_bin function is a good option. A pre-PG14 date_bin implementation here.