Oracle 獲取分組後的每組第一條資料(帶案例)
阿新 • • 發佈:2021-01-09
技術標籤:資料庫
主要程式碼源自於:https://www.codetd.com/article/6184073
select t.*
from (select row_number() over(partition by tor.order_name order by tor.order_id desc) rn, tor.* from tc_order tor) t
where t.rn = 1;
tc_order:表名
order_name:分組列名
order_id:排序列名(可以有多個排序)
row_number:分組序號
over(partition by tor.order_name order by tor. order_id desc):這是oracle的分析函式
案例:
需求,根據班級號分類找出每班第一名的記錄
select t.*
from (
select row_number()
over(partition by tor.classno order by tor.classno asc) rn, tor.*
from student tor
) t
where t.rn = 1;