答案 0 :(得分:1)
您似乎想要:
select t.*,
(100 - sum(quantity) over (order by id)) as running_qty
from t;
累积总和需要SQL Server 2012+。在早期版本中,使用apply
:
select t.*, (100 - sum_quantity)
from t cross apply
(select sum(t2.quantity) as sum_quantity
from t t2
where t2.id <= t.id
) t2;
答案 1 :(得分:0)
您也可以使用
CREATE TABLE T(
ID INT IDENTITY(1, 1),
Quantity INT
);
INSERT INTO T VALUES
(10),
(20),
(30),
(40),
(50),
(60);
SELECT T.*, 100-
( SELECT SUM(Quantity)
FROM T TT
WHERE TT.Quantity <= T.Quantity
) AS Results
FROM T;