I have SQL table with 3 columns – product, product version, and results(number).
I want to create a query that return the max result to each uniq version.
Simple data :
product | version | results |
---|---|---|
X | 1 | 50 |
X | 1 | 51 |
X | 1 | 53 |
X | 2 | 60 |
X | 2 | 62 |
X | 3 | 70 |
X | 4 | 80 |
X | 4 | 80 |
X | 4 | 80 |
Y | 1 | 50 |
Y | 2 | 60 |
Y | 3 | 70 |
Y | 4 | 80 |
In this table, the return value for product X version 1 will be 53, product X version 2 – 62, product X version 3 – 70 and so on.
how can i get this query ?
2
Answers
You can do it using the window function
row_number()
to sort data in descending order, then row withrn = 1
will be the highest :Demo here
Distinct on
can usually be the answer to "top one per group" type of problems: demo