Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select Attribiute B where Attribiute A is maximal after groupby in SQL

Given the following table:

ID Price Date
1 34 a
1 42 b
2 34 a

I would like to have one row per ID where the price was maximal

ID Price Date
1 42 b
2 34 a

Trying to groupby ID and selecting ID, Date, MAX(Price) results in the error GROUP BY clause with non aggregate functions

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use row_number.

SELECT *
FROM 
your_table_name
QUALIFY ROW_NUMBER() OVER (partition by id order by price desc) = 1;

The Qualify clause is used to filter the results of ordered analytical
function according to user‑specified search conditions. We can use
this conditional clause in the SELECT statement to get the particular
order values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading