-3

我有一个表有以下记录。

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

提前致谢...

4

1 回答 1

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 ║
  ╚═══════════╩═══════╩════════╩═════════╝

SQL FIDDLE中的演示

于 2013-05-08T07:32:08.520 回答