DB2 Toad SQL - 使用 Max 命令按特定列分组

DB2 Toad SQL - Group by Certain Columns using Max Command

我在处理以下查询时遇到了一些问题。我知道我需要按 ID 和类别分组,但我只想按 ID 分组,同时保持其余列基于 Rank 为最大值。有没有办法只按某些列分组?

select ID, Category, max(rank)
from schema.table1
group by ID

输入:

ID   Category   Rank
111  3          4
111  1          5
123  5          3
124  7          2

当前输出

ID   Category   Rank
111  3          4
111  9          1
123  5          3
124  7          2

期望的输出

ID   Category   Rank
111  1          5
123  5          3
124  7          2

您可以尝试使用 - row_number()

select * from
(
select ID, Category,rank, row_number() over(partition by id order by rank desc) as rn
from schema.table1
)A where rn=1

您可以使用:

select *
from table1
where (id, rank) in (select id, max(rank) from table1 group by id)

结果:

ID   CATEGORY  RANK 
---- --------- ---- 
111  1         5    
123  5         3    
124  7         2    

或者您可以使用 ROW_NUMBER() window 函数。例如:

select * 
from (
  select *,
    row_number() over(partition by id order by rank desc) as rn
  from table1
) x
where rn = 1

请参阅 db<>fiddle 中的 运行 示例。