2

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 enter image description here

Community
  • 1
  • 1
Hassan Mokdad
  • 5,832
  • 18
  • 55
  • 90

4 Answers4

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)
Drew
  • 24,851
  • 10
  • 43
  • 78
0

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
tranceporter
  • 2,241
  • 1
  • 21
  • 23
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
StevieG
  • 8,639
  • 23
  • 31
0

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
Kickstart
  • 21,403
  • 2
  • 21
  • 33