在sql中运行Balance

时间:2018-05-22 08:20:23

标签: sql sql-server tsql

我已尝试以下查询来获取帐户交易

select TranRef, TrnDate, AcNumber, AcName, DrCr, amount from Accounts
join Voucher
on Accounts.acid = voucher.accountno
join Transactions
on Transactions.TrnRef = Voucher.TranRef
where acnumber = 1010

Result of my query

但我希望结果采用以下格式

the Result which I want

1 个答案:

答案 0 :(得分:5)

使用窗口功能:

select TranRef, TrnDate, AcNumber, AcName, DrCr, amount,
       (case when DrCr= 'Dr' then amount else 0 end) as Debit,
       (case when DrCr= 'Cr' then amount else 0 end) as Credit,
       sum(case when DrCr = 'Cr' then amount else -amount end) over (partition by v.accountno order by TranRef) as Balance
from Accounts a
inner join Voucher v on a.acid = v.accountno
inner join Transactions t on t.TrnRef = v.TranRef
where v.accountno = 1010;