For each row in table line
there can be many rows in table line_version
. I need to find only N (let’s say 2) "latest" rows for each line
row. Latest here means the largest IDs.
For example, that’s how line_version
table rows look like (line_id
references the line
table):
id | line_id
-------+---------
10 | 1
20 | 1
30 | 1
40 | 1
50 | 2
60 | 2
70 | 2
Looking for the 2 latest line_version
row IDs per line
row, it should be (30, 40, 60, 70)
.
Globally, I can get 2 latest ones by simply doing:
SELECT id from line_version ORDER BY id DESC LIMIT 2
But how can I get the latest 2 per line_id
?
2
Answers
YOu can use the below with condition rownumber>=count1-(N-1).The sql fiddle here.For last row you can use rownumber>=count1.last two rows rownumber>=count1-1,three rows rownumber>=count1-2
To improve the performance you can do away with the count1 with the below using rownumber<=N.
If there are substantially more versions than just the two per line, avoid a sequential scan over
line_version
. This query using aLATERAL
subquery does just that, and should be much more efficient:fiddle
I added
NULLS LAST
mainly to defend against possible null values, which you haven’t ruled out. See:Sort by column ASC, but NULL values first?
Select first row in each GROUP BY group?
Be sure to have an index on
line_version
withline_id
as leading index field. Ideally:See: