[轉]SQL Server 2012 的 T-SQL 新功能 – 新的數據分析函數(LEAD、LAG)

當您須要在 SQL Server 中利用 T-SQL 比較結果集的每一列跟前一列或後一列的差別時,在過去可能須要利用 CURSOR 搭配臨時表變量,或是透過遞歸 CTE 來達到這個效果,現在 SQL Server 2012 提供了兩個分析用的函數(LEAD、LAG)來讓您更容易進行 ROW LEVEL 數據比較。ide

  • 如下程序代碼用來示範如何透過 LEAD 函數來計算每一列與後一列的 c2 字段相差幾天:
   1:  declare @t table
   2:  (
   3:      c1 int identity
   4:      ,c2 date
   5:  )
   6:  
   7:  insert into @t (c2)
   8:  select '20120101' 
   9:  union all
  10:  select '20120201' 
  11:  union all
  12:  select '20120110' 
  13:  union all
  14:  select '20120221' 
  15:  union all
  16:  select '20120121' 
  17:  union all
  18:  select '20120203' 
  19:  
  20:  select c1,c2
  21:      ,LEAD(c2) OVER (ORDER BY c2) as next_c2
  22:      ,DateDiff(day,c2,LEAD(c2) OVER (ORDER BY c2)) as diff
  23:  from @t
  24:  order by c2

 

執行結果:函數

 image

 

  • 如下程序代碼用來示範如何透過 LAG  函數來計算每一列與前一列的 c2 字段相差幾天:
   1:  declare @t table
   2:  (
   3:      c1 int identity
   4:      ,c2 date
   5:  )
   6:  
   7:  insert into @t (c2)
   8:  select '20120101' 
   9:  union all
  10:  select '20120201' 
  11:  union all
  12:  select '20120110' 
  13:  union all
  14:  select '20120221' 
  15:  union all
  16:  select '20120121' 
  17:  union all
  18:  select '20120203' 
  19:  
  20:  select c1,c2
  21:      ,LAG(c2) OVER (ORDER BY c2) as previous_c2
  22:      ,DateDiff(day,LAG(c2) OVER (ORDER BY c2),c2) as diff
  23:  from @t
  24:  order by c2

 

執行結果:spa

image

相關文章
相關標籤/搜索