计算不同行和列中的值之间的差异

时间:2011-12-29 06:25:21

标签: sql oracle oracle11g

请帮我解决以下问题。 假设我有一个表名为Data with 3行:Date1,Date2和visit window。我需要计算访问窗口值。它应该是日期1的第(n + 1)行和date2的第n行的差异。例如:Date1的第2行值和date2值的第1行的差值除以7.请帮助。

Table: Data
------------
Date1           Date2           VW
13-DEC-2011     15-DEC-2011     ?   
18-DEC-2011     16-DEC-2011     ?
21-DEC-2011     24-DEC-2011     ?

由于

1 个答案:

答案 0 :(得分:4)

select
  Date1, 
  Date2,
  lead(Date1) over (order by Date1) next_date1,
  ((lead(Date1) over (order by Date1)) - Date2)/7 as Diff
From DATA_TABLE

对于最后一行,您将无法获得任何大众,因为没有n + 1 Date1。

lead(column)函数返回column子句中指定的下一行over参数的值。

您可以找到示例和其他类似函数here

更新(对问题评论的回复 - 如何与其他专栏进行比较)

select 
  Date1,
  Date2,
  Diff,
  another_column,
  CASE 
    when Diff < another_column then 'it is lower'
    when Diff > another_column then 'it is higher'
    when Diff = another_column then 'are equal'
  END as comparation,
  CASE
    when round(diff -another_column,3) = 0 then 'almost equal'
    else 'definitely not equal'
  END as rounded_comparation
from(
    select
      Date1, 
      Date2,
      lead(Date1) over (order by Date1) next_date1,
      ((lead(Date1) over (order by Date1)) - Date2)/7 as Diff,
      another_column
    From DATA_TABLE
)