oracle运行减法

rbl8hiat  于 2021-07-29  发布在  Java
关注(0)|答案(4)|浏览(541)

我有以下数据。我想从总数量(80)中减去第一行,然后从qty1的前一行的数量中减去其余行。

QTY                      QTY1          DATE              TOTAL QTY
 2                        78         01-JAN-20             80
 1                        77         15-JAN-20
 46                       31         22-JAN-20
 16                       15         27-JAN-20

有办法吗?非常感谢您的帮助。谢谢

1bqhqjot

1bqhqjot1#

select
  t.*
 ,first_value(TOTAL_QTY)over(order by DT) - sum(QTY)over(order by DT) as QTY1
from t;

示例数据的完整示例:

with T(QTY, DT, TOTAL_QTY) as (
   select 2 , to_date('01-JAN-20','dd-mon-yy'),80   from dual union all
   select 1 , to_date('15-JAN-20','dd-mon-yy'),null from dual union all
   select 46, to_date('22-JAN-20','dd-mon-yy'),null from dual union all
   select 16, to_date('27-JAN-20','dd-mon-yy'),null from dual
)
select
  t.*
 ,first_value(TOTAL_QTY)over(order by DT) - sum(QTY)over(order by DT) as QTY1
from t;

结果:

QTY  DT          TOTAL_QTY  QTY1
2    2020-01-01  80         78
1    2020-01-15             77
46   2020-01-22             31
16   2020-01-27             15
oug3syen

oug3syen2#

sql表表示无序集。你的问题似乎取决于行的顺序。假设有一列表示排序。
使用累计和:

select t.*,
       sum(total_qty) over () - sum(qty) over (order by <ordering col>) as qty1
from t;

这是一把小提琴。

cx6n0qe3

cx6n0qe33#

类似这样的东西(cte只是你的数据):如果你以后再添加任何东西(在“总数量”列中),那么这也会被添加到“总数量”计算中(这对于添加到库存和从库存中减去是典型的)。

with d as

 (select  2   qty,                     78 qty1   ,      to_date('01-JAN-20','dd-mon-rr') datecol,             80 total_qty from dual union all
 select 1,                        77,         to_date('15-JAN-20','dd-mon-rr'),null from dual union all
 select 46 ,                      31,         to_date('22-JAN-20','dd-mon-rr'),null from dual union all
 select 16 ,                      15 ,        to_date('27-JAN-20','dd-mon-rr'),null from dual 
 )
select sum(total_qty) over (order by datecol) - sum(qty) over (order by datecol)
from d
7fyelxc5

7fyelxc54#

你可以做:

select
  qty, 
  first_value(total_qty) over(order by date) 
    - sum(qty) over(order by date) as qty1,
  date, total_qty
from t
order by date

相关问题