-3

I have a Table having following records.

---------------------------------------------------------
|VoucherDetailId    | VoucherId |   AccountId | Amount  |
---------------------------------------------------------
|    2              |    1      |         2   |  -5000  |
|    3              |    2      |         2   |  2000   |
|    15             |    8      |         2   |  777    |
---------------------------------------------------------

I want a query for below output..

------------------------------------------
| AccountId | Debit  | Credit  | Balance |
------------------------------------------
|   2       |   0    | 5000    | (5000)  |
|   2       |  2000  |   0     | (3000)  |
|   2       |  777   |   0     | (2223)  |
------------------------------------------

Thanks in Advance...

Shahid Iqbal
  • 2,095
  • 8
  • 31
  • 51

1 Answers1

3

Try this :-

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

Results :-

  ╔═══════════╦═══════╦════════╦═════════╗
  ║ ACCOUNTID ║ DEBIT ║ CREDIT ║ BALANCE ║
  ╠═══════════╬═══════╬════════╬═════════╣
  ║         2 ║     0 ║   5000 ║    5000 ║
  ║         2 ║  2000 ║      0 ║    3000 ║
  ║         2 ║   777 ║      0 ║    2223 ║
  ╚═══════════╩═══════╩════════╩═════════╝

Demo in SQL FIDDLE

praveen
  • 12,083
  • 1
  • 41
  • 49