Reputation: 101
I've been reading on lead and lag functions but I still don't get it. My sql syntax is as follows:
SELECT description, lag(description) over (ORDER BY transid ASC)
FROM transaction
WHERE transid = 20;
It's not returning the desired data. I have a table where transid is the primary key in int, and a column called description. I think the syntax is wrong because I want to return the whole row (all the column data) and I think this just returns one column of the previous row. How do I do that? Anybody?
Return an entire previous/next row.
Upvotes: 1
Views: 1797
Reputation: 522119
One option would be to use a subquery with LEAD
to restrict to the desired previous record:
WITH cte AS (
SELECT *, LEAD(transid) OVER (ORDER BY transid) transid_lead
FROM transaction
)
SELECT *
FROM cte
WHERE transid_lead = 20;
Upvotes: 1
Reputation: 272256
For previous row you can simply do this:
SELECT *
FROM transaction
WHERE transid < 20
ORDER BY transid DESC
LIMIT 1
For next row you reverse the conditions:
SELECT *
FROM transaction
WHERE transid > 20
ORDER BY transid ASC
LIMIT 1
Upvotes: 1