SQL 获取属性最大的条目

SQL get entries where on attribute is max

我有以下数据集:

id id_rev time
1 1 08.01.2022
1 0 31.02.2021
2 2 28.01.2017
2 1 25.07.2021
2 0 25.07.2021

我正在寻找一个 SQL 查询,它可以 return 每个 ID 一个条目,但只有 id_rev 最大的那个条目。所以在这种情况下它应该 return 这两行:

(id=1, id_rev=1,时间) (id=2, id_rev=2, 时间)

一种规范方法使用 ROW_NUMBER:

WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY id ORDER BY id_rev DESC) rn
    FROM yourTable t
)

SELECT id, id_rev, time
FROM cte
WHERE rn = 1
ORDER BY id;

另一种方法是使用现有逻辑:

SELECT id, id_rev, time
FROM yourTable t1
WHERE NOT EXISTS (
    SELECT 1
    FROM yourTable t2
    WHERE t2.id = t1.id AND t2.id_rev > t1.id_rev
);

@结果= SELECT *, 秩() OVER (PARTITION BY id ORDER BY id_rev DESC) AS Rank FROM dataset ORDER BY Rank;

@结果= SELECT * 从@结果 其中等级 = 1;