postgre[Postgres][SQL]窗口函数(计数/平均值),其中按周进行分区



有没有一种方法可以运行一个窗口函数,其中分区用于日期列,我需要在每周的时间间隔内聚合值。

例如,在这个数据集中

日期
01-01-2022 10
02-01-2022 15
10-01-2022 01
2022年1月11日 12
2022年1月20日 09
2022年1月25日 08

使用PG14+date_bin函数是一个不错的选择。此处为PG14之前的date_bin实现。

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

类似的东西?

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;

通常我不使用WW,但IW使用ISO周编号。但这取决于你。

最新更新