SQL :根据另一列的值在一列上保留一行最大值

SQL : Keep ONE row with max value on a column depending on value of another column

在 Whosebug 上有详细的文档说明如何根据某个组标识符 (SQL select only rows with max value on a column) 在一列中查找具有某个最大值的行的全部数据。

但是给定的解决方案将显示具有该最大值的所有行。 如果我们有 3 个列“ID, col1, col2” 并且我们想为每个 ID 保留具有最高 col1 值的行,但是如果有多个列,则只保留具有最低 col2 值的实例怎么办?

谢谢!

一种方法是rank()row_number()

select t.*
from (select t.*,
             row_number() over (partition by id order by col1 desc, col2 asc) as seqnum
      from t
     ) t
where seqnum = 1;

如果同一 ID 有重复的 max col1/min col2 时需要多行,则可以使用 rank()