Skip to content
Advertisement

select max from previous group

I am trying to get the MAX value from the previous group. Here is a sample table.

This query works for the first group (just by virtue of it being first, I think). Each group/cycle has the max time from the previous group/cycle. But I want it to start over with each group_id so that group 2 cycle 1 prev_max = 0 and group 2 cycle 2 prev_max = 4 and so on.

Advertisement

Answer

You can use aggregation and lag() – you just need to properly adjust the partition and order by clause of the window function:

Demo on DB Fiddlde:

GROUP_ID | CYCLE | MAX_TIME | PREV_MAX
-------: | ----: | -------: | -------:
       1 |     1 |        4 |        0
       1 |     2 |        8 |        4
       1 |     3 |       12 |        8
       2 |     1 |        4 |        0
       2 |     2 |        8 |        4
       2 |     3 |       12 |        8
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement