I have a table with the following schema:
uid | visit name | visit date | sales quantity |
---|---|---|---|
xyz | visit 1 | 2020-01-01 | 29 |
xyz | visit 2 | 2020-01-03 | 250 |
xyz | visit 3 | 2020-01-04 | 20 |
xyz | visit 4 | 2020-01-27 | 21 |
abc | visit 1 | 2020-02-01 | 29 |
abc | visit 2 | 2020-03-03 | 34 |
abc | visit 3 | 2020-04-04 | 35 |
abc | visit 4 | 2020-04-27 | 41 |
Each unique id has a few unique visits that repeat for every unique id, at every visit I have to calculate what the two most highest sales quantity is per user- across their prior visits(ascending order) up until the current visit named in the row for each unique id and excluding the current row.
output would be- the same table plus these columns
max sale | 2nd max sale | avg of both max sales |
---|
I have used window functions for the maximum value, but I am struggling to get the second highest value of sales for every user for every row. Is this doable using sql? If so what would the script look like?