我有一张表有以下记录。
---------------------------------------------------------
|VoucherDetailId | VoucherId | AccountId | Amount |
---------------------------------------------------------
| 2 | 1 | 2 | -5000 |
| 3 | 2 | 2 | 2000 |
| 15 | 8 | 2 | 777 |
---------------------------------------------------------
我想查询以下输出..
------------------------------------------
| AccountId | Debit | Credit | Balance |
------------------------------------------
| 2 | 0 | 5000 | (5000) |
| 2 | 2000 | 0 | (3000) |
| 2 | 777 | 0 | (2223) |
------------------------------------------
提前致谢...
答案 0 :(得分:3)
试试这个: -
Select AccountID,
case when SIGN(amount) = 1 then
Amount
ELSE
0
END as Debit,
case when SIGN(amount) = -1 then
abs(Amount)
ELSE
0
END as Credit,
(SELECT abs(SUM(Amount) )
FROM Sample b
WHERE b.VoucherDetailId <= a.VoucherDetailId) AS balance
from Sample a
结果: -
╔═══════════╦═══════╦════════╦═════════╗
║ ACCOUNTID ║ DEBIT ║ CREDIT ║ BALANCE ║
╠═══════════╬═══════╬════════╬═════════╣
║ 2 ║ 0 ║ 5000 ║ 5000 ║
║ 2 ║ 2000 ║ 0 ║ 3000 ║
║ 2 ║ 777 ║ 0 ║ 2223 ║
╚═══════════╩═══════╩════════╩═════════╝
中的演示