Forgive my example if it does not make sense. I’m going to try with a simplified one to encourage more participation.
Consider a table like the following:
-
dt | mnth | foo --------------+------------+-------- 2012-12-01 | December | ... 2012-08-01 | August | 2012-07-01 | July | 2012-06-01 | June | 2012-05-01 | May | 2012-04-01 | April | 2012-03-01 | March | ... 1997-01-01 | January |
If you look for the record with dt closest to today w/o going over, what would be the best way to also return the 3 records beforehand and 7 records after?
I decided to try windowing functions:
-
WITH dates AS ( select row_number() over (order by dt desc) , dt , dt - now()::date as dt_diff from foo ) , closest_date AS ( select * from dates where dt_diff = ( select max(dt_diff) from dates where dt_diff <= 0 ) ) SELECT * FROM dates WHERE row_number - (select row_number from closest_date) >= -3 AND row_number - (select row_number from closest_date) <= 7 ;
I feel like there must be a better way to return relative records with a window function, but it’s been some time since I’ve looked at them.
1 Answer