My table mixes (the interesting cols):
| id | article | ordenr | start_date |
|---|---|---|---|
| 1 | a | 10001 | 2024-01-01 |
| 2 | b | 10002 | 2024-01-03 |
| 3 | c | 10004 | 2024-01-02 |
| 4 | a | 10003 |
How do I get the previous article of ordernr based on start_date.
I have tried LAG and that works fine until I include the current ordernr (say 10004) then it just return NULL.
This works, I get a list with the correct previous article and ordernr.
SELECT TOP (1)
article, ordernr,
LAG(ordernr) OVER (ORDER BY start_date) AS prev_ordernr,
LAG(article) OVER (ORDER BY start_date) AS prev_article
FROM
mixes
ORDER BY
start_date DESC
But then I want a specific row, and add: where ordernr = '10004', it just returns NULL on in the prev_article and prev_ordernr.
How do I solve this?

LAGinto a subquery and then filter afterwards. But if it's only one row then anAPPLY (SELECT TOP 1might be better.