shubcbe
shubcbe

Reputation: 9

Calculate the difference between the value in different rows and columns

Please help me in solving the below query. Suppose if I have a table name as Data with 3 rows: Date1, Date2 and visit window. I need to calculate Visit window value. It should be the difference of (n+1)th row of date 1 and nth row of date2. For ex: Difference of 2nd row value of Date1 and 1st row of date2 value divided by 7. Please help.

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

Thanks

Upvotes: 0

Views: 1290

Answers (1)

Florin Ghita
Florin Ghita

Reputation: 17643

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

For the last row you won't get any VW, because there is no n+1 Date1.

lead(column) function returns value for the column parameter from the next row as specified in the over clause.

You can find examples and other similar functions here.

UPDATE (response to a question comment - how to compare with another column)

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
)

Upvotes: 4

Related Questions