开发者

SQL: grouping by column after sorting

Given a table structure with name and rank columns, with the possibility of there being duplicates for name, how can I get the rows unique by name, with maximum rank?

For example, assuming the following data:

+-------+-------+
| name  | rank  |
+-------+-------+
| a     | 1     |
| a     | 2     |
| b     | 10    |
| b     | 20    |
| c     | 100   |
| c     | 200   |
+-------+-------+

The query should return:

+-------+-------+
| a     | 2     |
| b     | 20    |
| c     | 200   |
+-------+-------+

I have the following solution that is extremely slow, which I suspect is O(N^2).

SELECT name, 
       rank 
FROM   books temp1 
WHERE  rank = (SELECT max(rank) 
                      FROM   book temp2 
                      WHERE  temp1.name = temp2.name) 

Can it be improved? Is there an altogether bett开发者_C百科er way to do this?

I'm using MySQL, and this will eventually have to be translated to JPA, so if there's a JPA/Hibernate idiom for this that would also be very appreciated.


select name, max(rank) as MaxRank
    from books
    group by name


SELECT name 
     , MAX(rank) AS rank
  FROM books
 GROUP BY name

That's the simplest query to return the result set in your example.


Normally all you would need is a standard group by

SELECT name, 
       max(rank) as rank
FROM   books temp1
GROUP BY name

But since it is MySQL, there is also an alternative

SELECT name, 
       rank
FROM   (
    SELECT name, rank
    FROM books
    ORDER BY name, rank desc) ordered
GROUP BY name
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜