Home > Software engineering >  [Postgres][SQL]Window functions (count/average) where partitioning by weeks
[Postgres][SQL]Window functions (count/average) where partitioning by weeks

Time:08-28

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.

CodePudding user response:

Something like this?

SELECT  date
    ,   value
    ,   TO_CHAR(date, 'WW')::INT AS weeknumber
    ,   AVG(value) OVER(PARTITION BY TO_CHAR(date, 'WW')::INT)
FROM    table_name
ORDER BY date;

Usually I don't use WW, but IW the ISO week numbering. But that's up to you.

CodePudding user response:

Using PG14 date_bin function is a good option. A pre-PG14 date_bin implementation here.

select date_bin('1 week', "Date", '2022-01-01') as "Week", 
       avg("Value") as "Avg"
from the_table 
group by "Week"; 
  • Related