Auto calculating columns in a sql table based on prevoius row data

后端 未结 2 1771
情书的邮戳
情书的邮戳 2021-01-20 15:14

I am using sql server as back-end for developing my application in asp.net c#. Now i need to create a table with an auto calculating column(closing balance) as shown below:<

相关标签:
2条回答
  • 2021-01-20 15:26

    Seems to me like you don't need really need recursion...

    CREATE FUNCTION dbo.GetClosingBalance(@Date date) RETURNS int AS
    BEGIN
        DECLARE @RetVal int
        SELECT
            @RetVal = SUM([in stock]) - SUM([out stock])
        FROM
            x
        WHERE
            [Date] <= @Date
        RETURN @RetVal
    END
    
    ALTER TABLE x ADD COLUMN [closing balance] AS (dbo.GetClosingBalance([Date]))
    
    0 讨论(0)
  • 2021-01-20 15:32

    Assumption

    1.Your table structure is like

    Date | In Stock | Out Stock
    

    2.You will insert a New Columns before calculating the balance.

    3.Date is an Primary Column (Unique + Not NULL)

    Taking the above assumptions:

    You have make a SP if you want to use in C#

    1.Create a temp table and assigned Row Number using Rank()

    select 
    rank() OVER (ORDER BY [Date]) as [Rank],
    t1.[Date],
    t1.[in stock],
    t1.[out stock]
    --,t1.[in stock]-t1.[out stock] balance
    into #temp1
    from (your table name)
    ;
    

    2.Now you will be using the above temp table to get the Balance

    WITH x AS
    (
        SELECT 
            [Rank],
            [Date],
            [in stock],
            [out stock],
            bal=([in stock]-[out stock])
        FROM #temp1
        WHERE [Rank] = 1
        UNION ALL
        SELECT 
            y.[Rank],
            y.[Date],
            y.[in stock],
            y.[out stock],
            x.bal+(y.[in stock]-y.[out stock])
        FROM x INNER JOIN #temp1 AS y
        ON y.[Rank] = x.[Rank] + 1
    )
    SELECT 
        [Date],
        [in stock],
        [out stock],
        Balance = bal
    FROM x
    ORDER BY Date
    OPTION (MAXRECURSION 10000);
    

    Here is the SQL Fiddle where you can verify.

    0 讨论(0)
提交回复
热议问题