这是使用LAG分析函数的方法之一,它允许您访问当前行之前的行。
-- sample of data from the question
with t1(col1, col2, col3) as(
select 178, 632, to_date('17/07/2013', 'dd/mm/yyyy') from dual union all
select 192, 785, to_date('18/07/2013', 'dd/mm/yyyy') from dual union all
select 265, 1012, to_date('21/07/2013', 'dd/mm/yyyy') from dual
) -- the query
select to_char(col1) -
decode( col3 - lag(col3, 1, col3) over(order by col3)
, 1
, lag(col1, 1, 0) over(order by col3)
, 0
) as col1
, to_char(col2) -
decode( col3 - lag(col3, 1, col3) over(order by col3)
, 1
, lag(col2, 1, 0) over(order by col3)
, 0
) as col2
, col3
from t1
结果:
COL1 COL2 COL3
--------------------------------------------------------
178 632 July, 17 2013 00:00:00+0000
14 153 July, 18 2013 00:00:00+0000
265 1012 July, 21 2013 00:00:00+0000
SQLFiddle 演示
作为另一种方法,您可以使用模型子句来获得相同的结果。
with t1(col1, col2, col3) as(
select 178, 632, to_date('17/07/2013', 'dd/mm/yyyy') from dual union all
select 192, 785, to_date('18/07/2013', 'dd/mm/yyyy') from dual union all
select 265, 1012, to_date('21/07/2013', 'dd/mm/yyyy') from dual
)
select c1
, c2
, col3
from t1
model
dimension by(row_number() over(order by col3) as rn)
measures( cast(null as number) as c1
, cast(null as number) as c2
, col1
, col2
, col3)
rules(
c1[rn] = decode( col3[cv()] - col3[cv() - 1]
, 1
, col1[cv()] - col1[cv() - 1]
, col1[cv()]
),
c2[rn] = decode( col3[cv()] - col3[cv() - 1]
, 1
, col2[cv()] - col2[cv() - 1]
, col2[cv()]
)
)
结果:
C1 C2 COL3
----------------------------------------------
178 632 July, 17 2013 00:00:00+0000
14 153 July, 18 2013 00:00:00+0000
265 1012 July, 21 2013 00:00:00+0000
SQLFiddle 演示