2013-03-05 41 views
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) 

回答

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