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?
You could outer join the previous values.
DATA USED
IF(OBJECT_ID('tempdb..#tmp_mixes') is not null)
DROP TABLE #tmp_mixes
CREATE TABLE #tmp_mixes (id int, article char(1), ordenr int, start_date datetime)
INSERT INTO #tmp_mixes
VALUES
(1, 'a', 10001, '2024-01-01'),
(2, 'b', 10002, '2024-01-03'),
(3, 'c', 10004, '2024-01-02'),
(4, 'a', 10003, null)
Something like:
SELECT
m.article,
m.ordenr,
m.start_date,
prev.ordenr AS prev_ordernr,
prev.article AS prev_article
FROM #tmp_mixes m
OUTER APPLY (
SELECT TOP 1
ordenr, article
FROM #tmp_mixes prev
WHERE prev.start_date < m.start_date
order by m.start_date desc
) prev
WHERE m.ordenr = 10004
order by m.start_date desc
Results
article | ordenr | start_date | prev_ordernr | prev_article |
---|---|---|---|---|
c | 10004 | 2024-01-02 00:00:00.000 | 10001 | a |