如果列中的值为负,则交换列值

时间:2017-04-27 21:34:02

标签: sql sql-server sql-server-2014

我有一个包含2列的表,即debit_amount和credit_amount。我需要从这个表中提取数据并交换值,如果它们是负数。

实际表格

TABLE A

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

必需的输出

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

谢谢!

2 个答案:

答案 0 :(得分:4)

使用case表达式。

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

答案 1 :(得分:0)

这不是执行此任务的最有效方法,但您也可以迭代每一行并使用游标检查值。如果您将来有其他逻辑,这可能会给您更大的灵活性。

declare @TABLE_A table ([Account No] int, CREDIT int, DEBIT int)
declare @TABLE_B table ([Account No] int, CREDIT int, DEBIT int)

insert into @TABLE_A
values 
(1, 500, 0),
(2, -322, 0),
(3, -869, 0),
(4, 0, 500),
(5, 0, -100)

set nocount on
set quoted_identifier off

declare @acct_no int, @cred int, @deb int 

declare iteration cursor GLOBAL STATIC for
        -- Begin statement for cursor array
        select [Account No], CREDIT, DEBIT from @TABLE_A
        -- End statement for cursor array

open iteration
  fetch first from iteration into @acct_no, @cred, @deb -- get first row

 while @@fetch_status=0 
 begin
 if @cred < 0
 begin
 set @deb = @cred * -1
 set @cred = 0
 end

 if @deb < 0 
 begin
 set @cred = @deb * -1
 set @deb = 0
 end

 insert into @TABLE_B
 values (@acct_no, @cred, @deb)

fetch next from iteration into @acct_no, @cred, @deb  --next row

end -- while @@FETCH_STATUS=0

close iteration

deallocate iteration

set nocount off

select * from @TABLE_B