簡體   English   中英

使用臨時變量從借方/貸方列計算 SQL 中的運行余額?

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

我想計算 SQL 服務器中的運行余額,但它在“=”和“:=”運算符附近顯示語法錯誤。 不知道如何增加價值。 我正在分享我正在使用的 SQL 查詢。

SQL查詢:

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')

在這里我得到:

select 語句中“=”符號附近的語法錯誤。

我用谷歌搜索了很多但找不到解決這個問題的方法。 我也使用過 ':=' 運算符,但沒有用。

我正在添加 output,這是我在應用“sum(t1.balance+t1.amount) as balance”后得到的,在此基礎上,余額列的值為 5970.12 我得到了這個....我還提到了預期的 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

請幫我擺脫困境...謝謝

您可以使用SUM() OVER( ORDER BY... )計算總計

您的查詢可以如下

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'

更新查詢:將第一行的初始余額添加到運行余額中。

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM