这是我的表结构
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
是否有其他方法可以在不使用光标的情况下获得所需的输出?
答案 0 :(得分:1)
获得运行余额的一种标准方法是在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