SQL select nth member of group

SELECT a.class,
(
    SELECT b.age 
    FROM users b 
    WHERE b.class = a.class
    ORDER BY age 
    LIMIT 1,1
) as age
FROM users a
GROUP BY a.class

Would get the 2nd youngest in each class. If you wanted the 10th youngest, you’d do LIMIT 9,1 and if you wanted the 10th oldest, you’d do ORDER BY age DESC.

Leave a Comment