在我的postgreSQL数据库中,我有一个包含日期和价格列的表。 ('transdate'和'price')
我想形成一个查询,在超过一年的日期范围内每周选择一行。
从另一个问题/答案中,我实现了这个代码,该代码适用于不到一年的日期范围:
;with cte as
(
select *,
row_number() over (partition by Extract (week from transdate) order by transdate desc) as rn
from "tablename" where transdate between '06-01-1999' and '06-01-1999'::timestamp + `'50 week'::interval
)
select transdate, price from cte where rn = 1 order by transdate;
然而,当我延长间隔超过50周时,它仍然只选择最多12个月。
如何重新编写此代码,以便从范围内的每周选择一个日期/价格?
答案 0 :(得分:1)
您的问题是,周数在年界处缠绕,但您希望同时查看周数和。幸运的是,你可以一次分开几件事:
row_number() over (
partition by extract(week from transdate),
extract(year from transdate)
order by transdate desc
) as rn