行之间的累计减法

时间:2018-11-08 22:52:54

标签: sql sql-server tsql

表1:
table1:

表2:
enter image description here

如何跨行从IncomingQuantity中累计减去Committed值(7)?这样结果将如下所示:
enter image description here

谢谢!

3 个答案:

答案 0 :(得分:2)

您需要一个累加和和一些算术运算:

select t.*,
       (case when running_iq - incomingquantity >= committed then 0
             when running_iq > committed then running_iq - committed
             else incomingquantity
        end) as from_this_row
from (select t2.*, t1.committed,
             sum(incomingquantity) over (order by rowid) as running_iq
      from table1 t1 cross join
           table2 t2
     ) t;

答案 1 :(得分:1)

您还可以将ROW_NUMBER()LAST_VALUE()等内置函数与LAG()一起使用

这是一个示例:

CASE

答案 2 :(得分:0)

我最终只是通过用户函数内的WHILE循环来完成此操作。我无法在100%的情况下正常工作的其他解决方案

相关问题