2017-06-19 154 views
0

我可以通過這個SQL獲得一些幫助並分割一個列字符串嗎?使用字符分隔符分割列

我目前得到的輸出

ID_Reference | Balance 
    203587   -902 
    203948   -111 

輸出我需要它:

ID_Reference | Balance 
    203587   902 
    203948   111 

我使用的代碼如下:

select AccountReference,CurrentBalance from SB_RentAccountBalances_V where CurrentBalance like '-%' 

謝謝,

+0

我假設你正在使用SQL Server,所以我增加了一個標籤。 –

回答

4

你會se EM想要的abs()功能:

select AccountReference, abs(CurrentBalance) as Balance 
from SB_RentAccountBalances_V 
where CurrentBalance < 0; 

誠然,我假設有一列名爲CurrentBalance實際上是一個數字,而不是一個字符串。

如果是字符串,則可以刪除前導-。在SQL Server,你可以使用:

select AccountReference, stuff(CurrentBalance, 1, 1, '') as Balance 
from SB_RentAccountBalances_V 
where CurrentBalance like '-%'; 
+0

完美,謝謝戈登:) – sqldan

+0

要添加,如果它實際上是一個字符串,將其轉換爲數字數據類型。 @sqldan –

0

我希望你想這一點,把

select AccountReference,abs(CurrentBalance) CurrentBalance from 
SB_RentAccountBalances_V where CurrentBalance like '-%' 
0

您只需要更換 - 用空白所需的輸出。試試下面的代碼

select AccountReference, 
     replace(CurrentBalance,'-','') as 'CurrentBalance' 
from SB_RentAccountBalances_V where CurrentBalance like '-%' 
0
SELECT ID_Reference, 
     SUBSTRING(Balance,CHARINDEX('-',Balance)+1,Len(Balance))AS Balance 
FROM SB_RentAccountBalances_V 
WHERE CHARINDEX('-',Balance)>0 
+0

感謝您使用此代碼段,它可能會提供一些即時幫助。通過展示*爲什麼*這是一個很好的解決方案,對未來的讀者會有更好的解決方案,這將爲它的教育價值提供一個合適的解釋[//大大提高](// meta.stackexchange.com/q/114762)但不完全相同的問題。請編輯您的答案以添加解釋,並指出適用的限制和假設。 –