在不使用游标的情况下生成此输出



这是我的表结构

item |Transaction Type| Qty_IN | Qty Out |Transaction Sequence
------|----------------|--------|-----------------------
item1| Beg. Balance   |   15   |    0    |  1
item1| Received Item  |   5    |    0    |  2
item1| Transfer Item  |   0    |    2    |  3
item1| Transfer Item  |   0    |    3    |  4

我想要的输出

item |Transaction Type| Qty_IN | Qty Out | End Bal
------|----------------|--------|---------|-------
item1| Beg. Balance   |   0    |    0    |  15
item1| Received Item  |   5    |    0    |  20
item1| Transfer Item  |   0    |    2    |  18
item1| Transfer Item  |   0    |    3    |  15

有没有另一种方法可以在不使用光标的情况下获得我想要的输出?

获取运行余额的一种标准方法是在 select 语句中使用相关子查询,该子查询计算进出金额之间差额的运行总和:

SELECT *,
(SELECT SUM(t2.Qty_IN - t2.Qty_OUT) FROM yourTable t2
WHERE t2.[Transaction Sequence] <= t1.[Transaction Sequence]) [End Bal]
FROM yourTable t1

相关内容

最新更新