Select longest continuous sequence
14
votes
2
answers
11428
views
I am trying to construct a query in PostgreSQL 9.0 that gets the longest sequence of continuous rows for a specific column.
Consider the following table:
lap_id (serial), lap_no (int), car_type (enum), race_id (int FK)
Where
lap_no
is unique for each (race_id, car_type)
.
I would like the query to produce the longest sequence for a given race_id
and car_type
, so it would return an int
(or long) that is highest.
With the following data:
1, 1, red, 1
2, 2, red, 1
3, 3, red, 1
4, 4, red, 1
5, 1, blue, 1
6, 5, red, 1
7, 2, blue, 1
8, 1, green, 1
For car_type = red and race_id = 1
the query would return 5
as the longest sequence of the lap_no
field.
I found a similar question here however my situation is a bit more straightforward.
(I would also like to know the longest sequence for a given car_type
for all races, but was planning to work that out myself.)
Asked by DaveB
(319 rep)
Feb 25, 2013, 04:06 PM
Last activity: Jul 29, 2022, 11:07 AM
Last activity: Jul 29, 2022, 11:07 AM