基于oracle中后续日期的数据差异

时间:2013-07-20 11:16:54

标签: oracle

我有一些记录(行)。 我希望根据所选日期记录的后续差异。 例如,对于2013年7月18日,最终结果应包含(record for 19/07/2013) - (record for 17/07/2013) 对于前 -

178     632    17/07/2013  
192     785    18/07/2013
265     1012   21/07/2013

然后结果应该是这样的 -

178-0      632-0      17/07/2013
192-178    785-632    18/07/2013
265-0      1012-0     21/07/2013

相当于

178     632    17/07/2013  
14      153    18/07/2013
265     1012   21/07/2013

1 个答案:

答案 0 :(得分:3)

以下是使用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 DEMO

作为另一种方法,您可以使用model clause来获得相同的结果。

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 Demo

相关问题