24

I have the following table:

ID NAME TIME
1  A    0
2  A    3
3  B    1

I am using the query below which produces:

SELECT * FROM `table` GROUP BY `NAME`
ID NAME TIME
1  A    0
3  B    1

And I want use GROUP BY to generate a result like this (discount sort by the TIME column):

ID NAME TIME
2  A    3
3  B    1
3
  • 1
    By reading your question, it is little unclear of how you want the fields to be sorted. Commented Dec 15, 2010 at 9:43
  • 1
    It's not 100% clear what result exactly you are trying to get. Perhaps try articulating what you actually want to do. Commented Mar 8, 2013 at 3:25
  • But what if I want "order by" go natural order? Commented Jan 22, 2015 at 9:42

5 Answers 5

29
SELECT NAME, MAX(TIME) as TIME 
FROM table 
GROUP BY time 
ORDER BY time DESC
Sign up to request clarification or add additional context in comments.

5 Comments

This actually worked for me. It gets me less info than the subquery-based solutions, but it's faster.
There is no assurance that the NAME column will be from the same row as MAX(TIME). It may well work given the above data or a small dataset but is by no means reliable. For a thorough discussion see stackoverflow.com/questions/14770671/…
It's work! Seems only ORDER BY clause can accept the alias in SELECT clause, nice trick.
Agree Rob Forrest's comment. You may get bug by this query depend on your use case.
It does not work for big data. ORDER BY is sorting the final result after GROUP BY.
7
 select * from (select * from table order by TIME DESC) t group by NAME

1 Comment

It will not work proper in my opinion, grupuping will be always the same, with and without DESC
5

Try this solution from here http://www.cafewebmaster.com/mysql-order-sort-group, it was able to solve my problem too :)

Sample:

SELECT * FROM 

(
select * from `my_table` order by timestamp desc
) as my_table_tmp

group by catid

order by nid desc

Comments

4

To get rows with highest time per group you could use a self join

select a.*
from demo a 
left join demo b on a.NAME =b.NAME and a.TIME < b.TIME
where b.NAME is null;

OR

select a.*
from demo a 
join (
  select NAME, max(`TIME`) as `TIME`
  from demo
  group by NAME
) b on a.NAME =b.NAME and a.TIME = b.TIME;

Demo

Comments

0

Well, you have to decide what you want to see in the ID and the time fields after the group by. As an example I'll select the MAX(ID) and the SUM(time), then order by totaltime desc.

SELECT MAX(id), name, SUM(time) AS totaltime
FROM YourTableName
GROUP BY name
ORDER BY totaltime DESC

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.