I have a SQL Server table with a date (session_date) and a value (price).
| session_date | price |
|---|---|
| 2022-12-31 | 10 |
| 2022-12-30 | 9 |
| 2022-12-29 | 5 |
| 2022-12-28 | 7 |
| 2022-12-27 | 2 |
| 2022-12-26 | 9 |
| 2022-12-25 | 3 |
| 2022-12-24 | 1 |
I want to compute the rolling maximum over the last 3 rows (dates) and retrieve the session_date associated with each maximum:
| session_date | price | rolling_max | rolling_last_date |
|---|---|---|---|
| 2022-12-31 | 4 | 9 | 2022-12-29 |
| 2022-12-30 | 4 | 9 | 2022-12-29 |
| 2022-12-29 | 9 | 9 | 2022-12-29 |
| 2022-12-28 | 7 | 7 | 2022-12-28 |
| 2022-12-27 | 2 | 4 | 2022-12-26 |
| 2022-12-26 | 4 | 4 | 2022-12-26 |
| 2022-12-25 | 3 | 3 | 2022-12-25 |
| 2022-12-24 | 1 | 1 | 2022-12-24 |
I'm using this query to compute the rolling maximum, but how can I get the associated session_date ?
select session_date
, price
, max(price) over (order by session_date rows between 3 preceding and current row) as rolling_max
from my_table
Try this :
To get
rolling_last_dateyou will have to join your result with the list the smallestsession_dateby price usingGROUP BYandMIN()Result :
Demo here