如何取分組最大值記錄

2021-09-06 04:27:18 字數 1719 閱讀 1463

分組最大值記錄

比如序號          名稱       數量       

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 分組 取第一條記錄

在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

如何取分組最大值記錄

分組最大值記錄 比如序號 名稱 數量 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 序...

Mysql按欄位分組取最大值記錄

在實際工作中,我們經常碰到這樣的工作情況,取出使用者訂單中給定使用者的最大單筆購買金額,此時,可以用到mysql的按字段分組取最大值,操作如下 表 user order 結構如下,我的操作是取出uid對應的最大的buy time 方法0 select uid,max buy time from us...

分組取最大值統計,過濾

匯率儲存,千分之5以內的,按照日期,幣種,匯率,匯率浮動分組。首先分組,按照日期,幣種,匯率,匯率浮動,然後分組統計 日期,幣種,匯率 1的並且,浮動範圍在千分5以內。如果有2條匯率,一條記錄大於千分之5,一條記錄小於千分之5,分組統計數目就大於1,就過濾掉。如果匯率正常的且有多條,然後取max 最...