如何将正值和负值从单列分隔到不同列

时间:2019-01-12 07:40:13

标签: sql-server

Account            Positive_Amount         Negative_Amount
------------       ..............         ...................
10101               5000
10012               6000
10101                                     -2000
10012                                     -9000
10101               2000
10012               7000
10101                                     -1000
10012                                     -1500

结果必须像

call

3 个答案:

答案 0 :(得分:7)

这并不复杂,只需使用此查询即可。希望对您有所帮助:

--first add your new column--
ALTER TABLE Accounts
 ADD Negative_Amount decimal(10,2) NULL

--update your columns--
UPDATE Accounts
SET Negative_Amount = CASE WHEN Amount<0 THEN Negative_Amount ELSE NULL END
,Amount = CASE WHEN Amount>=0 THEN Negative_Amount ELSE NULL END

--this sp helps you to rename objects--
EXEC SP_RENAME 'Accounts.Amount' , 'Positive_Amount', 'COLUMN'

这是在您希望表中进行结构更改的情况下。如果您只想要结果,其他答案就是解决方案。

答案 1 :(得分:4)

使用CASE子句非常简单:

SELECT Account,
       CASE WHEN Amount >= 0 THEN Amount ELSE NULL END AS Positive_Amount,
       CASE WHEN Amount < 0 THEN Amount ELSE NULL END AS Negative_Amount
FROM YourTable;

答案 2 :(得分:2)

一个简单的CASE就可以做到。

SELECT account, 
      (CASE WHEN Amount >= 0 THEN Amount ELSE Null END) AS Positive_Amount,
      (CASE WHEN Amount <  0 THEN Amount ELSE Null END) AS Negative_Amount
FROM tbl;