• OK, just saw your use of LAG which means SS20012.

    But you're making completely wrong use of it.

    If you delete one of the rows with cgm='5' from your data and run your script the results become a lot worse.

    In your final select display the dr column and you'll see this right away.

    Also, no dense_rank needed here. Rank is sufficient.