I looked at some SQL Server running total examples, but I can't manage thing like this.
I have a table where I have columns id, name, type of operation, date, value. I want to calculate balance for each record. Balance should be calculated like this:
Starting balance must be 0 and then if operation type is IN there will be plus, if operation is OUT there will be minus. Each next record should see previous record balance and then +value or -value depending on operation Type.
This operation should be ordered by date (not Id).
For example, if the table looks like this:
ID Name  Op_Type Date       Value
1  box   Out     2017-05-13 15
2  table In      2017-04-31 65
3  box2  In      2017-05-31 65
then result should look like this
ID Name  Op_Type Date       Value Balance
2  table In      2017-04-31 65     65
1  box   Out     2017-05-13 15     50
3  box2  In      2017-05-31 65     115
result of this code :
select *,
       sum(case when Op_Type = 'Out' then -Value else Value end)Over(Order by [Date]) as Balance
From Yourtable
is:
ID  Date        Type        Value       Balance
143 2016-12-31  In          980         664.75
89  2016-12-31  Out         300         664.75
90  2016-12-31  Out         80          664.75
But I expect the following result:
ID  Date        Type        Value       Balance
143 2016-12-31  In          980         980
89  2016-12-31  Out         300         680
90  2016-12-31  Out         80          600