Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres - Rank based on consecutive values

How can I create a rank that restarts at 1 when the consecutive sequence is broken?

(Click on the Image below)

The table below represent the flow of a User. His total journey consists of 8 steps, the page indicates which page he is on during each step. I would like to create a rank, that resets when the page changes. The tricky part is getting the rank in (step 6, page 1) to reset to 1 and not continue at 4. Partitioning by Page is not enough, as I want the rank to restart when the user changes back to Page 1 and continue. The table contains the results I would like to achieve, I just do not know how to do this in Postgres.

Table Rank

like image 941
phil Avatar asked Nov 25 '25 09:11

phil


1 Answers

You can assign a group using the difference of row numbers approach and then use row_number() to assign the ranking:

select step, page,
       row_number() over (partition by page, seqnum - seqnum_p order by step) as ranking
from (select t.*,
             row_number() over (order by step) as seqnum,
             row_number() over (partition by page order by step) as seqnum_p
      from t
     ) t;

To understand why this works, look at the results of the subquery. You will see how the difference between the two seqnum values identifies consecutive rows with the same value.

like image 86
Gordon Linoff Avatar answered Nov 28 '25 05:11

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!