Select item, Name, Begin, Debit, Credit, (Begin + Debit - Credit) as Balance
From (Select item, Name, Begin, Debit, Credit From TableName)D
Select item, Name, Begin, Debit, Credit, (Begin + Debit - Credit) as Balance
From TableName
declare @Table1 table
([item] varchar(1), [ItemDate] datetime, [Begin] int, [Debit] int, [Credit] int)
;
INSERT INTO @Table1
([item], [ItemDate], [Begin], [Debit], [Credit])
VALUES
('A', '2017-01-01 00:00:00', 100, 20, 30),
('A', '2017-01-02 00:00:00', 90, 10, 40)
;
select
*
, [begin] + sum(debit-credit) over(partition by item order by itemdate) run_total
from @table1
resutlt:
+------+---------------------+-------+-------+--------+-----------+
| item | ItemDate | Begin | Debit | Credit | run_total |
+------+---------------------+-------+-------+--------+-----------+
| A | 01.01.2017 00:00:00 | 100 | 20 | 30 | 90 |
| A | 02.01.2017 00:00:00 | 90 | 10 | 40 | 50 |
+------+---------------------+-------+-------+--------+-----------+
select
*
, sum(credit) over(partition by item order by itemdate)
- sum(debit) over(partition by item order by itemdate)
run_total
from @table1
with t as (
select '1001' TrxNo, '2017-01-01 00:00:00' TrxDate, 'Opening' Item, 0 Debit, 100 Credit
union select '1002', '2017-01-02 00:00:00', 'A', 20, 30
union select '1003', '2017-01-03 00:00:00', 'B', 10, 40
union select '1003', '2017-01-03 00:00:00', 'B', 60, 15
)
select TrxNo, TrxDate, Item,
IsNull(sum(credit - debit) over (order by TrxNo ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),0) as Opening,
Debit, Credit,
sum(credit - debit) over (order by TrxNo rows UNBOUNDED PRECEDING) as cumulative_sales
from t
TrxNo TrxDate Item Opening Debit Credit cumulative_sales
1001 2017-01-01 00:00:00 Opening 0 0 100 100
1002 2017-01-02 00:00:00 A 100 20 30 110
1003 2017-01-03 00:00:00 B 110 10 40 140
1003 2017-01-03 00:00:00 B 140 60 15 95
and result that you look for