1

我的查询返回下表:

|  CODE  |    DATE    |  VALUE  |
|  123   | 30/06/2012 |   11    |
|  231   | 01/07/2012 |   22    |
|  321   | 02/07/2012 |   11    |
|  234   | 03/07/2012 |   11    |

我需要它来创建基于 DATE 和 VALUE 列的列。所以它必须把今天的价值广告除以前几天

因此,一旦查询运行,结果应该是:

|  CODE  |    DATE    |  VALUE  |  RET  |
|  123   | 30/06/2012 |   11    |       |
|  231   | 01/07/2012 |   22    |  2.0  |
|  321   | 02/07/2012 |   11    |  0.5  |
|  234   | 03/07/2012 |   11    |  0.0  |

据我所知:

SELECT
    CODE
    DATE
    VALUE 
    (DATE/(TO_DATE(DATE)-1)) AS RET
FROM
    ....

但显然你不能将一个日期除以另一个日期并期望得到一个数字。

谢谢

4

1 回答 1

2

为了能够访问列的先前值,您可以使用滞后分析函数:

   -- sample of data from your question
   SQL> with t1(CODE, DATE1, VALUE1) as(
      2    select 123, to_date('30/06/2012', 'dd/mm/yyyy'), 11  from dual union all
      3    select 231, to_date('01/07/2012', 'dd/mm/yyyy'), 22  from dual union all
      4    select 321, to_date('02/07/2012', 'dd/mm/yyyy'), 11  from dual union all
      5    select 234, to_date('03/07/2012', 'dd/mm/yyyy'), 11  from dual
      6  )-- the query
      7  select code
      8       , Date1
      9       , Value1
     10       , to_char(value1 / lag(value1, 1) over(order by date1), '999990.0') ret
     11    from t1
     12  ;

结果:

      CODE DATE1           VALUE1      RET
---------- -----------   ----------   ---------
       123 30/06/2012         11 
       231 01/07/2012         22       2.0
       321 02/07/2012         11       0.5
       234 03/07/2012         11       1.0
于 2012-11-26T12:16:08.593 回答