Suposición
1. La estructura de tu tabla es como
Date | In Stock | Out Stock
2.Insertarás una Nuevas Columnas antes de calcular el balance
.
3. La fecha es una Primary Column
(Único + No NULL )
Tomando las suposiciones anteriores:
Has hecho un SP si desea utilizar en C#
1.Crea una tabla temporal y asignó Row Number
usando 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.Ahora usará la temp table
anterior para obtener el saldo
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);
Aquí está el SQL Fiddle donde puedes verificar.