Just Some Things to Read
SQL function last_value
19 October 2022
Sometimes it is good to read the Server documentation carefully when you need in depth information about a function. For a query I needed the last value within a partition. As an example for each customer I needed all sales dates and also the most recent sales date, something like this:
| Customer | Sales Date | Last Sales Date |
|---|---|---|
| John Doe | 12/12/2021 | 5/5/2022 |
| John Doe | 5/5/2022 | 5/5/2022 |
| Forrest Gump | 1/1/2020 | 8/8/2022 |
| Forrest Gump | 4/4/2021 | 8/8/2022 |
| Forrest Gump | 8/8/2022 | 8/8/2022 |
To be honest, I didn't know by heart what it was and how to use it. So I read the online documentation about the over clause and I forgot to use the correct windows frame. The default window frame is RANGE UNBOUNDED PRECEDING AND CURRENT ROW (as mentioned in the documentation) and now I understood my query result and it was "correct" with respect to its default windows frame. I changed the query to use the correct window frame with ROWS BETWEEN UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING and right now I was happy with the results!
Of course I could solve this with e.g. a nested sub query but I want to solve this with the available function. And I believe this is a more elegant solution. Maybe the other solution is better from a performance point of view, I didn't test this.
Happy SQL!