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

achieve "order by" before "group by" in mysql

i have a DB with this structure

id, UserID, price, Date

,1, 10.00, 2000-01-01
,1, 25.00 ,2022-02-01
,2, 12.00 ,2000-01-05
,2, 13.00 ,2001-01-05
,2, 24.00 ,2022-01-01
,3, 23.00 ,2022-01-01

i want to show the price for each user based on newest date.
So just 1 row per UserID (latest date)

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

if we query above table. results need to be like this:

    ,1, 25.00 ,2022-02-01
    ,2, 24.00 ,2022-01-01
    ,3, 23.00 ,2022-01-01

i have tried those 2 commands but they are not working

SELECT UserID,price,Datee FROM (SELECT UserID,price,Datee FROM tbl
ORDER BY UserID ASC,datee DESC) as tb_temp GROUP BY UserID

also this

SELECT UserID,price,max(Datee) FROM tbl Group by UserID ORDER BY UserID ASC,datee DESC

this command show latest date but price is not based on that

so i need something like ORDER BY datee then group by userID or LIMIT 1 per userID

>Solution :

You could try this, it’s not the most efficient because it uses a sub-query:

SELECT t.UserID, t.price, t.Datee
FROM tbl t
JOIN tbl on t.id = (SELECT id FROM tbl WHERE UserID = t.UserID ORDER BY Datee DESC LIMIT 1)
GROUP BY UserID

The idea is to join the table to itself by finding the latest row for the user id.

I made this sql fiddle to test it: http://sqlfiddle.com/#!9/63d495/2

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