Skip to content
Advertisement

Min and max value per group keeping order

I have a small problem in Redshift with with grouping; I have a table like following:

INPUT

I want to obtain this output:

If I do a simple Min and Max date grouping by the value, it doesn’t work.

Advertisement

Answer

This is an example of a gap-and-islands problem. If there are no time gaps in the data, then a difference of row numbers is a simple solution:

Why this works is a little tricky to explain. But if you look at the results of the subquery, you will see how the difference between the row numbers identifies adjacent rows with the same value.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement