View Single Post

   
  #3 (permalink)  
Old 02-28-2008, 09:31 AM
Captain Paralytic
 
Posts: n/a
Default Re: Order By and Group By


howa wrote:
> hi all,
>
> I have a table below...
>
> c1 c2 c3
> 1 1 a
> 1 2 b
> 2 1 c
> 2 2 d
> 3 1 e
> 3 2 f
>
>
> I want to get (1,2,b), (2,2,d), (3,2,f), i.e. group by c1, which having
> the largest c2, and select the row
>
> but the following quesy can't work...
>
> SELECT *
> FROM `table_1`
> GROUP BY c1
> ORDER BY c2
>
> how to do this? thanks.


Sheesh, this old chestnut comes up sooooo often! There are so many
recent threads about this question, which Strawberry and I have
answered, I'm amazed that no one can find the answer by searching the
newsgroup.
Oh well, here we go with the answer again...

SELECT t1. *
FROM `table_1` t1
LEFT JOIN `table_1` t2 ON t1.c1 = t2.c1 AND t1.c2 < t2.c2
WHERE t2.c1 IS NULL

Dimitre's one will only work on recent versions of MySQL but is nowhere
near as efficienct as the above method.

Reply With Quote