user5718409 user5718409 - 7 months ago 29
SQL Question

Selecting penultimate record from a table

I have the following table:

enter image description here

I need to select penultimate record matching some

probID
and
studentID
. How should I do that?

Answer
SELECT * FROM tbl
    WHERE (probID = 2) AND (studentID = 2)
    ORDER BY id DESC
    LIMIT 1 OFFSET 1

PS: This will not return any result for (probID, studentID) = (2,13), because no penultimate record exists for this combination. If this is not desired, you will need to specify what should happen in this case.

Comments