1. 程式人生 > >oracle資料鄰行(隔行)處理

oracle資料鄰行(隔行)處理

--語法
--向後 LAG (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
--向前 LEAD (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
select A,lead(A,1,A)over(order by px asc)LEAD_DATA,lag(A,1,A)over(order by px asc)LAG_DATE,B,C,D,PX,type from
(
  select 1 A,2 B,3 C,4 D,1 px,'s' type from dual
  union all 
  select 12 A,20 B,3 C,12 D,3 px,'s' type from dual
   union all 
  select 5 A,6 B,7 C,8 D,2 px,'m' type from dual
   union all 
  select 5 A,6 B,7 C,8 D,4 px,'m' type from dual
)
--在些基礎上可做靈活擴充套件處理[分組排序]
select A,lead(A,1,A)over(partition by type order by px asc)LEAD_DATA,lag(A,1,A)over(partition by type order by px asc)LAG_DATE,B,C,D,PX,type from
(
  select 1 A,2 B,3 C,4 D,1 px,'s' type from dual
  union all 
  select 12 A,20 B,3 C,12 D,3 px,'s' type from dual
   union all 
  select 5 A,6 B,7 C,8 D,2 px,'m' type from dual
   union all 
  select 5 A,6 B,7 C,8 D,4 px,'m' type from dual
)
--在些基礎上可做靈活擴充套件處理[相加、相減、乘、除、字條串操作等]
select A,(A/lead(A,1,A)over(order by px asc))LEAD_DATA,(B+lag(A,1,A)over(order by px asc))LAG_DATE,B,C,D,PX,type from
(
  select 1 A,2 B,3 C,4 D,1 px,'s' type from dual
  union all 
  select 12 A,20 B,3 C,12 D,3 px,'s' type from dual
   union all 
  select 5 A,6 B,7 C,8 D,2 px,'m' type from dual
   union all 
  select 5 A,6 B,7 C,8 D,4 px,'m' type from dual
)
lag 和lead 有三個引數,第一個引數是列名,第二個引數是偏移的offset,第三個引數是超出記錄視窗時的預設值