简体   繁体   English

选择具有最大列值的行由另一列分组,没有嵌套的选择语句

[英]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 Rows with Maximum Column Value group by another Column的副本,但我想选择具有最大列值的行,作为 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
)

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.其中ID, Rank, Name是表架构,我想先按 Name 按结果分组,然后从每个 Name 组中选择一行,具体取决于哪一个具有最高的 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.不确定您是否只是想排除嵌套选择,以及加入 aginst 子选择是否可以接受。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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