Given a table such as the one below, how can I ask PostgreSQL to return the first set of n
rows in which one column has a certain value (code=0
) and the values of the second column (named segment
) are all the same, and the sequence of IDs is not broken.
For n=4
, the result should be id
's 12, 13, 14, 15
(i.e. the first four id
's where code=0
and the values of segment
are the same - in this case 2
).
CREATE TABLE foo
AS
SELECT *
FROM ( VALUES
( 1, 0, 0 ),
( 2, 0, 0 ),
( 3, 0, 0 ),
( 4, 0, 1 ),
( 5, 0, 1 ),
( 6, 0, 1 ),
( 7, 1, 1 ),
( 8, 0, 1 ),
( 9, 1, 2 ),
( 10, 0, 2 ),
( 11, 1, 2 ),
( 12, 0, 2 ), -- HERE
( 13, 0, 2 ), -- HERE
( 14, 0, 2 ), -- HERE
( 15, 0, 2 ), -- HERE
( 16, 0, 3 )
) AS t(id,code,segment);
n
limited? Or it is a known number not greater then a certain value (say 10)?10, 12, 13, 14
- but I now see why that only served to confuse, since it was already clear from the question title and first sentence. I will remove that note.