如何取分組最大值記錄

來源:互聯網
上載者:User

 分組最大值記錄

 


比如
    序號          名稱       數量       
       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

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.