Search code examples
sqlsql-serversql-server-2014

Swap the column Values if value in a column is negative


I have a table which has 2 columns i.e. debit_amount and credit_amount. I need to extract the data from this table and swap the values if they are negative.

Actual Table

TABLE A

Account no   CREDIT    DEBIT
   1           500      0
   2          -322       0
   3          -869       0
   4           0         500
   5           0        -100

Required Output

  Account no   CREDIT    DEBIT
       1           500      0
       2           0       322 
       3           0       869
       4           0        500
       5          100        0

Thanks!


Solution

  • Use a case expression.

    select accountno
    ,case when credit=0 and debit < 0 then -1*debit 
          when credit < 0 then 0 
     else credit end as credit
    ,case when debit=0 and credit < 0 then -1*credit 
          when debit < 0 then 0 
     else debit end as debit
    from tblA