【问题标题】:Splitting a column using character delimiter使用字符分隔符拆分列
【发布时间】:2017-06-19 10:51:25
【问题描述】:

我可以在此 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 '-%'

谢谢,

【问题讨论】:

  • 我假设你使用的是 SQL Server,所以我添加了一个标签。

标签: sql sql-server split ssms


【解决方案1】:

您似乎想要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 '-%';

【讨论】:

  • 要添加,如果它实际上是一个字符串,则将其转换为数字数据类型。 @sqldan
【解决方案2】:

我希望你想要这个

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

【讨论】:

    【解决方案3】:

    您只需将 - 替换为所需的输出即可。试试下面的代码

    select AccountReference,
           replace(CurrentBalance,'-','') as 'CurrentBalance'
    from SB_RentAccountBalances_V where CurrentBalance like '-%'
    

    【讨论】:

      【解决方案4】:
      SELECT ID_Reference,
             SUBSTRING(Balance,CHARINDEX('-',Balance)+1,Len(Balance))AS Balance 
       FROM SB_RentAccountBalances_V
       WHERE CHARINDEX('-',Balance)>0
      

      【讨论】:

      • 感谢您提供此代码 sn-p,它可能会提供一些即时帮助。一个正确的解释would greatly improve 其教育价值通过展示为什么这是一个很好的解决问题的方法,并将使它对未来有类似但不相同的问题的读者更有用。请edit您的答案添加解释,并说明适用的限制和假设。
      猜你喜欢
      • 2011-12-26
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      相关资源
      最近更新 更多