Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

Date    in stock    out stock   closing balance
2/3/2013    0             0          0
3/3/2013    10            5          5
5/3/2013    10            52        -37
6/3/2013    52            7          8
7/3/2013    6             50        -36
8/3/2013    10            12        -38

Here the closing balance for each day depends on the closing balance of the previous day

For Example, today's closing balance=(previous day closing balance+today's instock)-(today's outstock) When i add a new entry dated 4/3/2013 to the table,the table must be shown as below

Date    in stock    out stock   closing balance
2/3/2013    0            0              0
3/3/2013    10           5              5
4/3/2013    20          15             10
5/3/2013    10          52            -32
6/3/2013    52           7             13
7/3/2013    6           50            -31
8/3/2013    10          12            -33

i made this using microsoft excel(using formulas),but i need to achieve it using sql server table for my application. Any help will be appreciated.

like image 486
Kiranramchandran Avatar asked Dec 07 '25 06:12

Kiranramchandran


1 Answers

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.

like image 131
Prahalad Gaggar Avatar answered Dec 08 '25 19:12

Prahalad Gaggar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!