如何编写一个函数来计算列值,如图所示?
这是我尝试过的代码:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION RunningBal
(
-- Add the parameters for the function here
@Dr INT,
@Cr INT,
@Code NVARCHAR(5)
)
RETURNS INT
AS
BEGIN
-- Declare the return variable here
DECLARE @CurrentRunningBal INT
-- Add the T-SQL statements to compute the return value here
DECLARE @PreviouBal INT
SET @PreviouBal = (SELECT TOP(1) [RunningBal] FROM Test WHERE Code = @Code ORDER BY ID DESC)
if(@PreviouBal IS NULL)
SET @PreviouBal = 0
SET @CurrentRunningBal = @PreviouBal + @Dr - @Cr
-- Return the result of the function
RETURN @CurrentRunningBal
END
GO
当我尝试执行此操作时,我收到以下错误,并且不知道如何解决它。
答案 0 :(得分:1)
最有可能的问题是您的列名与函数名RunningBal
完全相同,但我无法重现该行为。
在Sql Server 2014
中,您可以使用窗口函数来运行总计,例如:
DECLARE @t TABLE
(
id INT ,
code CHAR(1) ,
dramount MONEY ,
cramount MONEY
)
INSERT INTO @t
VALUES ( 1, 'a', 200, 0 ),
( 2, 'a', 250, 0 ),
( 3, 'b', 300, 0 ),
( 4, 'b', 0, 150 ),
( 5, 'a', 300, 0 ),
( 6, 'a', 100, 0 )
SELECT * ,
SUM(dramount - cramount) OVER ( PARTITION BY code ORDER BY id ) AS runningTotal
FROM @t
ORDER BY id
输出:
id code dramount cramount runningTotal
1 a 200.00 0.00 200.00
2 a 250.00 0.00 450.00
3 b 300.00 0.00 300.00
4 b 0.00 150.00 150.00
5 a 300.00 0.00 750.00
6 a 100.00 0.00 850.00