更新表中的列

时间:2017-11-04 14:28:05

标签: sql oracle plsql oracle11g

我有一个要求,其中有一个如下表

Invoice Date        Year    Amount
1001    04-NOV-15   2015    100
1001    04-NOV-16   2016    400
1001    04-NOV-17   2017    600
1002    01-OCT-17   2014    1000

我期待最后一列应该计算时尚的差异

Invoice Date        Year    Amount    Calculation
1001    04-NOV-15   2015    100       0
1001    04-NOV-16   2016    400       ((04-NOV-16)-(04-NOV-15))/(400-300)
1001    04-NOV-17   2017    600       ((04-NOV-17)-(04-NOV-16))/(600-400)
1002    01-OCT-14   2014    1000      0
1002    01-OCT-18   2018    2000      ((01-OCT-18)-(01-OCT-14))/(2000-1000)
1003    01-JAN-14   2014    1000      0

计算栏是必需的,

我尝试了下面的查询,它给出了金额差异

select invoice, 
       date_value,
       Year_va,
       amount,
       amount-lag(amount) over (partition by invoice

                                                order by date_value,invoice
                                               ) diff                                      
 from sample;

尝试时

select invoice, 
       date_value,
       Year_va,
       amount,
       MOD(date_value-lag(date_value),amount-lag(amount)) over (partition by invoice

                                                order by date_value,invoice
                                               ) diff                                      
 from sample;

它因窗口函数错误而失败。

请有人帮忙吗....

2 个答案:

答案 0 :(得分:0)

如果您想要差异,为什么要使用mod()

( (date_value - lag(date_value) over (partition by invoice order by date_value) ) /
  (amount - lag(amount) over (partition by invoice order by date_value) )
) as ratio

您可能希望coalesce()获取0而不是NULL s(您的查询不会处理此问题,但您的示例数据表明您可能希望这样做)。

答案 1 :(得分:0)

正如戈登所指出的,您可以使用lag功能和coalesce如下所示来获得所需的结果。

SELECT t1.*
    ,coalesce((
            date_value - lag(date_value) OVER (
                PARTITION BY invoice ORDER BY date_value
                )
            ) / (
            amount - lag(amount) OVER (
                PARTITION BY invoice ORDER BY date_value
                )
            ), 0) AS ratio
FROM table1 t1;

您还可以使用ANSI等效min/max以及ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING,如下所示。

SELECT t1.*
    ,coalesce((
            date_value - min(date_value) OVER (
                PARTITION BY invoice ORDER BY date_value ROWS BETWEEN 1 PRECEDING
                        AND 1 PRECEDING
                )
            ) / (
            amount - min(amount) OVER (
                PARTITION BY invoice ORDER BY date_value ROWS BETWEEN 1 PRECEDING
                        AND 1 PRECEDING
                )
            ), 0) AS ratio
FROM table1 t1;

<强>结果:

INVOICE      DATE_VALUE             YEAR    AMOUNT  RATIO
-----------------------------------------------------------
1001         04.11.2015 00:00:00    2015    100     0
1001         04.11.2016 00:00:00    2016    400     1.22
1001         04.11.2017 00:00:00    2017    600     1.8250
1002         01.10.2017 00:00:00    2014    1000    0

<强> DEMO