Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order By with Group By

Is there an efficient way to do an order by and group by so that you get a specific item from each group (from the order by).

//This is the best way i have come up with.
SELECT D.*
FROM (
    SELECT *
    FROM devices
    ORDER BY time
) AS D
GROUP BY D.location
like image 496
ThePrimeagen Avatar asked Jun 28 '11 14:06

ThePrimeagen


2 Answers

This worked for me

SELECT *
FROM (SELECT *
      FROM col
      ORDER BY col DESC,date DESC)a
GROUP BY col
like image 180
Samuel Ramzan Avatar answered Sep 25 '22 16:09

Samuel Ramzan


SELECT *
FROM devices
GROUP BY D.location
ORDER BY time --ASC or DESC default is ASC i believe

No need for sub-queries

like image 43
Naftali Avatar answered Sep 23 '22 16:09

Naftali