سؤال

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?

هل كانت مفيدة؟

المحلول

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);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top