分組最大值記錄
比如
序號 名稱 數量
1 A 20
2 A 10
1 B 20
2 B 40
3 B 10
1 C 20
2 C 40 |
子查詢:
select * from 表 where (序號,名稱) in (select max(序號),名稱 from 表 group by 名稱)
分析函數:
select 序號 , 名稱 , 數量 from
(select 序號 , 名稱 , 數量
,row_number() over(partition by 名稱 order by 序號 desc ) rn
form tab_name )
where rn=1
或
select 序號 , 名稱 , 數量 from
(select 序號 , 名稱 , 數量
, max(序號) over(partition by 名稱) rn
form tab_name )
where rn=序號
注意:max的欄位只能是number類型欄位,如果是date類型的,會提示錯誤。date類型用上面的row_number()來做就可以了。
Oracle 分組 取第一條記錄id apply_id
1 1
2 1
3 1
4 2
5 2
6 3
7 3
8 3
取出
id apply_id
3 1
5 2
8 3
select alx_a.id
from
(select id,apply_id,rownum rid from 表) alx_a,
(select id,apply_id,rownum rid from 表) alx_b
where alx_a.apply_id = alx_b.apply_id and alx_a.id <= alx_b.id
group by alx_a.id,alx_a.apply_id
having count(*) = 1
分組並取每組中的前n條記錄
在oracle中有一資料表exam_result(成績記錄表),
表中的一條記錄描述了“某個班某個學生某次考試的成績"
create table EXAM_RESULT
(
ID NUMBER(10) not null, --主鍵
CLASSID NUMBER(10) not null, -- 班級id,關聯到班級表
USERID NUMBER(10) not null, --使用者id,關聯到使用者表
EXAMID NUMBER(10) not null, --試卷id,關聯到試卷表
RESULT NUMBER(3) --成績
)
現在要求統計完成了試卷id為1,2,3的成績的前3名
即完成了試卷id為1的前3名,完成了試卷id為2的前3名,完成了試卷id為3的前3名
select * from (
select
e.classid,
e.userid,
e.examid,
e.result,
row_number() over (partition by e.examid order by e.examid, e.result desc) rn
from exam_result e
where e.examid in (1,2,3)
) where rn <= 3