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

SQL query to return maximum value for each identifier

In a table ‘purchases’ is a list of items bought at a ‘cost’ by each ‘user_id’

One user can make many purchases, so there are many duplicate user_id’s in the table.

What could be an SQL query that would return only the most expensive item that each user had purchased?

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

What is the error in the following attempt?

SELECT user_id, MAX(cost) 
FROM purchases
WHERE user_id 
IN (SELECT user_id FROM purchases)

>Solution :

You need to group by each user:

SELECT user_id, MAX(cost) 
FROM purchases
GROUP BY user_Id;
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