0

像这样的表:

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)
4

1 回答 1

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

另请注意,您使用的这种“古怪更新”方法没有记录,不受支持,并且可能会产生不可预测的结果。

http://sqlperformance.com/running-totals

于 2013-03-05T23:21:58.487 回答