Antagelse
1. Din tabelstruktur er som
Date | In Stock | Out Stock
2. Du vil indsætte en Nye kolonner før du beregner balance
.
3. Dato er en Primary Column
(Unik + Ikke NULL )
Ud fra ovenstående antagelser:
Du har lavet en SP hvis du vil bruge i C#
1.Opret en temp-tabel og tildelt Row Number
ved at bruge 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. Nu skal du bruge ovenstående temp table
for at få balancen
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);
Her er SQL Fiddle hvor du kan verificere.