How can I select one row for each week in a date range that spans more than a year?
In my postgreSQL data base, I have a table with columns of dates and prices. ('transdate' and 'price')
I would like to form a query which selects one row for each week over a date range which spans more than one year.
From another question/answer here, I implemented this code which works for date ranges of less than a year:
;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;
However, when I extend the interval greater than 50 weeks, it still only selects a max of 12 months.
How can I re-write this code to select one date/price from every week in the range?
Your problem is that week numbers wrap around at year boundaries but you want to look at the week number and the year at the same time. Lucky for you, you can PARTITION BY several things at once:
row_number() over ( partition by extract(week from transdate), extract(year from transdate) order by transdate desc ) as rn