计算SQL RunningTotal列

问题描述 投票:0回答:2

我有这样一张桌子:

我希望RunningTotal列应该像下面这样计算:Balance = Deposit + Balance和Withdraw-Balance,例如我想要RunningTotal表必须是这样的:

    AccountNo       Deposit   Withdraw    RunningTotal
---------------    --------    --------    --------------
    2014002         1000         0         1000
    305002            0         500        500
    50021           2500        100        2900
    54201           6000         0         8900

帮我!

sql sql-server tsql
2个回答
3
投票

这是使用2012年sum() over()作品的一种方式。考虑到你有一个id/date列来订购结果

select AccountNo, Deposit, Withdraw, 
       RunningTotal = sum(Deposit-Withdraw)over(order by id Rows between UNBOUNDED PRECEDING and current row )
from Yourtable

适用于旧版本

select AccountNo, Deposit, Withdraw, 
       cs.RunningTotal
from Yourtable a
cross apply(select sum(Deposit-Withdraw)
            from Yourtable b 
            where a.id>=b.id) cs (RunningTotal)

1
投票

在SQL Server中尝试计算列,将列RunningTotal更改为计算列,该列根据Deposit - Withdraw计算每行的值。像这样:

CREATE TABLE #temp
(
    AccountNo VARCHAR(50),
    Deposit   NUMERIC(19,2),
    Withdraw  NUMERIC(19,2),  
    RunningTotal AS (Deposit - Withdraw)
)

INSERT INTO #temp (AccountNo, Deposit, Withdraw)
    SELECT '1234', 100, 50

SELECT * FROM #temp

现在结果将是这样的

enter image description here

我在存款中加20,RunningTotal将自动更改

UPDATE #temp 
SET Deposit = Deposit + 20

SELECT * FROM #temp

enter image description here

如果每个帐户有多行,并且想要分别计算每行的RunningTotal(假设您的表上有主键/标识列 - 如下所示)

CREATE TABLE YourTable
(
    SeqNo INT IDENTITY(1,1),
    AccountNo VARCHAR(50),
    Deposit NUMERIC(19,2),
    Withdraw NUMERIC(19,2),  
    RunningTotal AS (Deposit - Withdraw)
)

创建一个UDF来计算值,就像这样

CREATE FUNCTION dbo.fn_CalculateBalance
    (@AccountNo VARCHAR(50), @Id INT)
RETURNS NUMERIC(19,2)
AS
BEGIN
    DECLARE @RunningTotal NUMERIC(19,2)

    SELECT @RunningTotal = SUM(Deposit) - SUM(Withdraw) 
    FROM YourTable 
    WHERE AccountNo = @AccountNo 
      AND SeqNo <= @Id

    RETURN @RunningTotal
END

现在改变这样的RunningTotal

CREATE TABLE YourTable
(
    SeqNo INT IDENTITY(1,1),
    AccountNo VARCHAR(50),
    Deposit NUMERIC(19,2),
    Withdraw NUMERIC(19,2),  
    RunningTotal AS (dbo.fn_CalculateBalance(AccountNo, SeqNo))
)

或者,如果您想在Date(标识列)上使用SeqNo列。更改UDF以使用SeqNo列替换Date的检查。

当您查看消息时,您可以多次看到消息“1行受影响”。那是因为你有这个计算列并在计算列中传递日期值。

© www.soinside.com 2019 - 2024. All rights reserved.