0

我有一些记录(行)。我想要基于所选日期的后续记录差异。比如,对于 2013 年 7 月 18 日,最终结果应包含(record for 19/07/2013) - (record for 17/07/2013) For Ex -

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
4

1 回答 1

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 演示

作为另一种方法,您可以使用模型子句来获得相同的结果。

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 演示

于 2013-07-20T11:36:07.640 回答