Question

Say I have a table my_table that has a column ID and has another column Date and all these records are unique.

I would like to select for all IDs, the records with the lowest N Dates. If I want to do this for N = 1, I have the following below

SELECT
    *
FROM my_table r
WHERE
    r.Date = (SELECT Min(Date) FROM my_table WHERE ID = r.ID)

How do I generalise this for higher N?

Was it helpful?

Solution

SQLite allows the following syntax:

SELECT r.*
FROM my_table r
WHERE r.Date IN (SELECT Date FROM my_table WHERE ID = r.ID ORDER BY Date LIMIT 5);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top