递归Oracle查询以计算彼此依赖的两个值

时间:2017-12-17 19:57:17

标签: oracle recursive-query

我的这张表有材料库存数据:

Date(MM/DD) |received_qty| returned_qty | used_qty
01/01       |   5000     |    0         |  3500
01/02       |    0       |    0         |  1500
01/03       |   7500     |    0         |  1250
01/04       |    0       |    0         |    0

我需要再添加两列来计算“起始数量”和“每日库存”,假设如下:

  • “开始数量”在第一天为零,之后为“每日” 股票“从前一天开始。

  • “每日库存”是“开始数量”+ received_qty - returned_qty - used_qty

如您所见,每个值都相互依赖......

因此,添加这两列后,数据会是这样的:

Date(MM/DD) |Start_qty  |received_qty| returned_qty | used_qty | daily_stock
01/01       |    0      |   5000     |    0         |  3500    |   1500
01/02       |   1500    |    0       |    0         |  1500    |    0
01/03       |     0     |   7500     |    0         |  1250    |   6250
01/04       |   6250    |    0       |    0         |    0     |   6250

我确信这些列可以使用Oracle中存在start withconnect by子句的递归查询生成,但我对脚本很难...

1 个答案:

答案 0 :(得分:1)

尝试此查询

Select t.*,
     Coalesce( 
       Sum( "received_qty" - "returned_qty" - "used_qty" )
       Over ( order by "Date" ) ,
       0) as daily_stock,
     Coalesce(
       Sum( "received_qty" - "returned_qty" - "used_qty" )
       Over ( order by "Date" 
              Rows between unbounded preceding
              And 1 preceding ), 
       0) as start_quantity

from table1 t

演示http://sqlfiddle.com/#!4/94417/13

|                  Date | received_qty | returned_qty | used_qty | DAILY_STOCK | START_QUANTITY |
|-----------------------|--------------|--------------|----------|-------------|----------------|
| 2001-01-01 00:00:00.0 |         5000 |            0 |     3500 |        1500 |              0 |
| 2001-01-02 00:00:00.0 |            0 |            0 |     1500 |           0 |           1500 |
| 2001-01-03 00:00:00.0 |         7500 |            0 |     1250 |        6250 |              0 |
| 2001-01-04 00:00:00.0 |            0 |            0 |        0 |        6250 |           6250 |