1. 程式人生 > >Oracle處理當前行與其之前行

Oracle處理當前行與其之前行

平移: lag/lead over 函式

  1. oralce內建的高階函式,可以獲取到當前查詢結果集中每一行的前幾行,相當於做了垂直方向的平移
  2. 要注意的函式作用域是此次查詢結果集,雖然提供了分組的功能,只是對當前結果集的分組
  3. lagover
  4. sample
with tmp as(
select '1' id ,'aa' name ,'19' age from dual union all
select '31' id ,'aa' name ,'31' age from dual union all
select '2' id ,'bb' name ,'20'
age from dual union all select '3' id ,'CC' name ,'21' age from dual ) select a.*, lag(age,1) over (order by name, id asc) lag, a.age - lag(age,1) over (order by id asc) lag1 from tmp a;

這裡寫圖片描述

填充: 關聯

  1. 通過利用rownum做一次逆序排列,對null值用其之前不為0的數值填充
  2. with a as (), b as () select * from a; 快取表資料
  3. sample
with test as (
select rownum rn, id, age from(
select '1' id , 19 age from dual union all
select '2' id , null age from dual union all
select '3' id , null age from dual union all
select '4' id , 21 age from dual union all
select '5' id , 0 age from dual  )
),
test2 as (select * from test order
by rn desc) select tm.id, tm.age, ( select t2.age from test2 t2 where t2.rn <= tm.rn and t2.age > 0 and rownum = 1) agepad from test tm;

這裡寫圖片描述