按 ID 和 select MAX 分组

GROUP BY ID and select MAX

晚上好, 我正在 Oracle 中处理这样的 table:

ID BALANCE SEQ
1 102 13
1 119 15
2 50 4
3 20 11
3 15 10
3 45 9
4 90 5
5 67 20
5 12 19
6 20 1

我想select,对于每个 ID,具有 MAX(SEQ) 的 BALANCE。

所以最终结果将是:

ID BALANCE SEQ
1 119 15
2 50 4
3 20 11
4 90 5
5 67 20
6 20 1

我该怎么做? 我尝试了几个 Group by queries 但没有成功。 感谢您的帮助

一种方法是使用 keep 聚合:

select id,
       max(balance) keep (dense_rank first order by seq desc) as balance,
       max(seq)
from t
group by id;

你可以使用普通的rank()

SELECT ID, BALANCE, SEQ FROM ( 
select 
ID, BALANCE, SEQ, RANK() OVER (PARTITION BY ID ORDER BY SEQ DESC)  ranks
from t 
) WHERE ranks = 1

示例演示

    SELECT ID, BALANCE, SEQ FROM ( 
SELECT ID, BALANCE, SEQ, RANK() OVER (PARTITION BY ID ORDER BY SEQ DESC)  ranks 
FROM ( 
SELECT 1 ID,    102 BALANCE,    13 SEQ FROM dual UNION all
SELECT 1,       119,    15  FROM dual UNION all
SELECT 2,       50,     4   FROM dual UNION all
SELECT 3,       20,     11  FROM dual UNION all
SELECT 3,       15,     10  FROM dual UNION all
SELECT 3,       45,     9   FROM dual UNION all
SELECT 4,       90,     5   FROM dual UNION all
SELECT 5,       67,     20  FROM dual UNION all
SELECT 5,       12,     19  FROM dual UNION all
SELECT 6,       20,     1   FROM dual 
)
) WHERE ranks = 1

您可以将其添加到您的大查询中,如下所示

SELECT ID, BALANCE, SEQ FROM ( 
select 
ID, BALANCE, SEQ, RANK() OVER (PARTITION BY ID ORDER BY SEQ DESC)  ranks
from (**YOUR BIG QUERY HERE**) 
) WHERE ranks = 1