組內排序和組外排序的sql寫法

2021-09-12 02:53:29 字數 2590 閱讀 6137

id       班級        成績

1          a              23

2          b              33

3          c               43

4          a               53

6          b               55

7          c               33

請教1:組外排序,以組為單位排序,並且給序號,以班級為分組

排成序號     id       班級        成績

1        1           a             23

1        4           a             53

2        2           b             33

2        7           b             55

3        3           c             43

3        6           c             33

請教2:組內排序

排成序號     id       班級        成績

1        1           a             23

2        4           a             53

1        2           b             33

2        7           b             55

1        6           c             33

2        3           c             43

oracle :

第一種(組外排序):

with tmp(id,  班級  , 成績)as

(select '1','a','23' from dual union all

select '2','b','33' from dual union all

select '3','c','43' from dual union all

select '4','a','53' from dual union all

select '6','b','55' from dual union all

select '7','c','33' from dual)

select sum(r)over(order by rownum) as 序號,id,班級,成績 from

(select t.*,

case

when lag(班級) over(partition by 班級 order by 成績) is null then

1else

0end r

from tmp t)

具體例項(ps:實際專案中的)

或者使用lag函式

lead () 下乙個值 

lag() 上乙個值

如果lag(t.id) 根據id分組,如果上一條資料id是不相同(空的)(不存在的),那麼標號數字位1,否則為0,最後合計為序號。

select sum(r) over(order by rownum) num, f.* from (

select t.*,

case

when lag(t.id) over(partition by t.id order by t.ldate) is null then

1else

0end r

from vb_orders t,vb_orders_chr oc

where t.id = oc.order_id

) f

第二種(組內排序):

with tmp(id,  班級  , 成績)as

(select '1','a','23' from dual union all

select '2','b','33' from dual union all

select '3','c','43' from dual union all

select '4','a','53' from dual union all

select '6','b','55' from dual union all

select '7','c','33' from dual)

select row_number() over(partition by 班級 order by 成績) as 序號, t.*

from tmp t

例項:

select row_number() over(partition by c.id order by c.ldate) as 序號, c.*

from (select t.*

from vb_orders t,vb_orders_chr oc

where t.id = oc.order_id) c

內排序和外排序

內排序 指在排序期間資料物件全部存放在記憶體的排序。外排序 指在排序期間全部物件太多,不能同時存放在記憶體中,必須根據排序過程的要求,不斷在內,外存間移動的排序。根據排序元素所在位置的不同,排序分 內排序和外排序。內排序 在排序過程中,所有元素調到記憶體中進行的排序,稱為內排序。內排序是排序的基礎。...

內排序和外排序的理解

內排序 指在排序期間資料物件全部存放在記憶體的排序。外排序 指在排序期間全部物件太多,不能同時存放在記憶體中,必須根據排序過程的要求,不斷在內,外存間移動的排序。根據排序元素所在位置的不同,排序分 內排序和外排序 內排序 在排序過程中,所有元素調到記憶體中進行的排序,稱為內排序。內排序是排序的基礎。...

mysql group by組內排序

mysql group by組內排序 首先是組外排序 select z.create time,z.invoice id from qf invoice log z where z.type 102 group by z.invoice id order by z.create time desc ...