简体   繁体   中英

Select Rows with maximum column value grouped by another column without nested select statement

I know that this is a duplicate of Select Rows with Maximum Column Value group by Another Column but I want to select rows that have the maximum column value,as group by another column , but without nested select statement , I know it can be done like this:

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
)

where ID, Rank, Name is the table schema, and I want to group by results by Name first, and then choose one row from each Name group, depending on which one has the highest Rank.

Attached is a sample of the table I want to select from在此处输入图片说明

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)

As mentioned in the other answer, the only other alternative that I know of, is using Common Table Expressions:

;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
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

Not sure whether you are just trying to exclude the nested select, and whether joining aginst a subselect would be acceptable. If so:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM