选择具有按其他列分组的最大列值的行,而不使用嵌套的select语句

时间:2012-11-21 11:02:57

标签: mysql sql sql-server

我知道这是Select Rows with Maximum Column Value group by Another Column的副本,但我想选择具有最大列值的行,作为另一列的分组,但没有嵌套的select语句,我知道可以这样做:

SELECT
    T.Name,
    T.Rank,
    T.ID
FROM MyTable T
WHERE T.Rank = (
    SELECT MAX( T1.Rank) FROM MyTable T1
    WHERE T1.Name= T.Name
)

其中ID, Rank, Name是表架构,我想先按名称按结果分组,然后从每个名称组中选择一行,具体取决于哪一行具有最高等级。

附件是我想要选择的表格的示例 enter image description here

4 个答案:

答案 0 :(得分:2)

mysql> SELECT t1.nm, t1.rank,t1.id
 FROM mytable t1
 LEFT JOIN (
   SELECT nm, max(rank) as top
   FROM mytable t2
   GROUP BY nm
 ) AS t2 ON t1.nm=t2.nm AND t1.rank = t2.top
 WHERE t2.nm IS not NULL
 ORDER BY nm;

+----+------+---------+
| nm | rank | id      |
+----+------+---------+
| m  |   -1 | b7kjhsf |
| n  |   13 | d3sf    |
+----+------+---------+
2 rows in set (0.00 sec)

mysql> select * from mytable;

+----+------+----------+
| nm | rank | id       |
+----+------+----------+
| n  |   11 | asfd     |
| n  |   11 | bsf      |
| n  |   11 | zzasdfsf |
| n  |   13 | d3sf     |
| n  |   11 | effesf   |
| n  |   10 | yxxgesf  |
| n  |   11 | bkhjusf  |
| m  |   -1 | b7kjhsf  |
| m  |   -4 | cdfgabsf |
+----+------+----------+
9 rows in set (0.00 sec)

答案 1 :(得分:0)

正如在另一个答案中所提到的,我所知道的唯一其他选择是使用公用表表达式:

;WITH CTE AS
(
    T.Name,
    T.Rank,
    T.ID,
    ROW_NUMBER() OVER
       (PARTITION BY Name ORDER BY Rank DESC)
    AS RowNumber
    FROM MyTable
)

SELECT *
FROM CTE
WHERE RowNumber = 1

答案 2 :(得分:0)

SELECT Name, Id, Rank FROM 
(
    SELECT T.Name, T.Id, T.Rank, RANK() OVER (PARTITION BY T.Name ORDER BY T.Rank DESC) = 1 AS NameRank
    FROM MyTable T
)
WHERE NameRank = 1

答案 3 :(得分:0)

不确定您是否只是尝试排除嵌套选择,以及是否可以接受加入aginst的子选择。如果是这样的话: -

SELECT
    T.Name,
    T.Rank,
    T.ID
FROM MyTable T
INNER JOIN (SELECT Name, MAX(Rank) AS MaxRank FROM MyTable GROUP BY Name ) T1
ON T.Name = T1.Name
AND T.Rank = T1.MaxRank