简体   繁体   中英

Calculate the running balance in SQL from Debit/Credit column with temporary variable?

I want to calculate running balance in SQL server but it is showing syntax error near '=' and ':=' operator. Don't know how to add values. I am sharing my SQL query that I am using.

SQL query:

declare @tempbal decimal(18,0)
set @tempbal = (select top 1 (balance)
from t1
left outer join t2 on t2.accountno = t1.accountno
left outer join t3 on t1.cc = t2.dc
where accountNo = '1234')

  
select 
'Date',
'Description',
isnull(case when t1.amount<0 then (t1.amount) end,0) as Debit,
isnull(case when t1.amount>0 then (t1.amount) end,0) as Credit,
 (@tempbal = @tempbal + (t1.amount) as balance
from t1
left outer join t2 on t2.accountno = t1.accountno
left outer join t3 on t1.cc = t2.dc
where accountNo = '1234')

Here I am getting:

incorrect syntax error near '=' sign in select statement.

I have googled a lot but couldn't find a solution to resolve this. I have also used ':=' operator but it didn't work.

I am Adding output which I am getting after applying ' sum(t1.balance+t1.amount) as balance ' Here balance column has value 5970.12 on the basis of this I got this....I also mentioned the expected output.

   Date     | Desc | Amount | Balance   | Expected Balance
2020-01-01  |Ref12 |  6.8   | 5976.92   | 5976.92
2020-01-06  |ref34 |  850   | 6820.12   | 6826.92
2020-01-22  |ref44 | 22032  | 28002.12  | 28858.92
2020-02-07  |ref54 | -26000 | -20029.88 | 2858.92

Please, help me out of this mess... Thanks

You can use SUM() OVER( ORDER BY... ) for running total

your query can be as follow

select [Date],
       [Description],
       isnull(case when t1.amount<0 then (t1.amount) end,0) as Debit,
       isnull(case when t1.amount>0 then (t1.amount) end,0) as Credit,
       SUM(t1.amount) OVER (ORDER BY [Date]) as balance
from   t1
       left outer join t2 on t2.accountno = t1.accountno
       left outer join t3 on t1.cc = t2.dc
where  t1.accountNo = '1234'

Updated Query: added initial balance from first row to the running balance.

select [Date],
       [Description],
       isnull(case when t1.amount<0 then (t1.amount) end,0) as Debit,
       isnull(case when t1.amount>0 then (t1.amount) end,0) as Credit,
       case when row_number() over (order by [Date]) = 1
            then balance
            else 0
            end
       + SUM(t1.amount) OVER (ORDER BY [Date]) as balance
from   t1
       left outer join t2 on t2.accountno = t1.accountno
       left outer join t3 on t1.cc = t2.dc
where  t1.accountNo = '1234'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM