表格如下:
Description Type Amount
Record 1 10
Record 2 20
Record 1 5
Record 3 10
如何在运行金额中排除某种类型的记录?因此,如果我排除类型3,我的运行总和将变为:
Description Type Amount RunningSum
Record 1 10 10
Record 2 20 30
Record 1 5 35
我正在使用更新局部变量技术。我有什么:
DECLARE @Amount DECIMAL(18, 4)
SET @Amount = 0
UPDATE MY_TABLE
SET RunningTotal = @Amount
,@Amount = @Amount + ISNULL(Amount, 0)
答案 0 :(得分:1)
看起来像一个简单的WHERE
子句,没有?
WHERE [Type] <> 3;
示例(虽然不确定为什么将变量声明为DECIMAL
):
DECLARE @d TABLE
(
Description CHAR(6),
[Type] INT, -- bad column name choice!
Amount DECIMAL(18,4),
RunningTotal DECIMAL(18,4) NULL
);
INSERT @d VALUES
('Record',1,10,NULL),
('Record',2,20,NULL),
('Record',1,5 ,NULL),
('Record',3,10,NULL);
DECLARE @rt DECIMAL(18, 4) = 0; -- calling this @Amount is confusing
-- it is storing the running total!
UPDATE @d
SET @rt = RunningTotal = @rt + Amount
WHERE [Type] <> 3;
SELECT Description, [Type], Amount, RunningTotal FROM @d;
结果:
Description Type Amount RunningTotal
----------- ---- ------- ------------
Record 1 10.0000 10.0000
Record 2 20.0000 30.0000
Record 1 5.0000 35.0000
Record 3 10.0000 NULL
另请注意,您使用的这种“古怪更新”方法未记录,不受支持,并且可能会产生不可预测的结果。