Skip to content
Advertisement

SQL Window Function – Number of Rows since last Max

I am trying to create a SQL query that will pull the number of rows since the last maximum value within a windows function over the last 5 rows. In the example below it would return 2 for row 8. The max value is 12 which is 2 rows from row 8.

For row 6 it would return 5 because the max value of 7 is 5 rows away.

I tried the following:

This gets me to the max values but I am unable to efficiently determine how many rows away it is. I was able to get close using multiple variables within the SELECT but this did not seem efficient or scalable.

Advertisement

Answer

You can calculate the cumulative maximum and then use row_number() on that.

So:

I think this works for your sample data. It might not work if you have duplicates.

In that case, you can use date arithmetic:

EDIT:

Here is an example using row number:

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