【问题标题】:cast(SUBSTRING with decimal强制转换(带小数的SUBSTRING
【发布时间】:2015-09-04 11:35:11
【问题描述】:

我有这条线可以正常工作并将我的列变成一个数字

       case when Auth_Amt  LIKE '%DAY%'  then cast(SUBSTRING(Auth_Amt FROM 1 FOR POSITION('/DAY' IN Auth_Amt) - 1) as numeric) when Auth_Amt  LIKE '%TAX%'  then cast(SUBSTRING(Auth_Amt FROM 1 FOR POSITION(' ' IN Auth_Amt) - 1) as numeric)
            when Auth_Amt  LIKE '%SCHG%'  then cast(SUBSTRING(Auth_Amt FROM 1 FOR POSITION(' ' IN Auth_Amt) - 1) as numeric)
            else 0
       end as Amt_Day

我可以添加什么以使其也返回两个小数点。现在是整数带回来了。

【问题讨论】:

    标签: sql-server-2008 casting numbers substring decimal


    【解决方案1】:

    你可以这样试试:

    case when Auth_Amt  LIKE '%DAY%'  then CAST(cast(SUBSTRING(Auth_Amt FROM 1 FOR POSITION('/DAY' IN Auth_Amt) - 1) as decimal(13,2)) as decimal(13,2))
         when Auth_Amt  LIKE '%TAX%'  then CAST(cast(SUBSTRING(Auth_Amt FROM 1 FOR POSITION(' ' IN Auth_Amt) - 1) as decimal(13,2)) as decimal(13,2))
         when Auth_Amt  LIKE '%SCHG%' then CAST(cast(SUBSTRING(Auth_Amt FROM 1 FOR POSITION(' ' IN Auth_Amt) - 1) as decimal(13,2)) as decimal(13,2))
          else 0
    end as Amt_Day
    

    一般来说,你必须像这样投射它:

    CAST(yourField as decimal(13,2))
    

    【讨论】:

    • 我要把它放在这条线下面吗?
    • 当 Auth_Amt LIKE '%TAX%' 然后转换(SUBSTRING(Auth_Amt FROM 1 FOR POSITION(' ' IN Auth_Amt) - 1) as numeric)
    • @Matt:- 你可以试试CAST(cast(SUBSTRING(Auth_Amt FROM 1 FOR POSITION(' ' IN Auth_Amt) - 1) as numeric) as decimal(13,2))
    • 太棒了。那种工作。正在发生的事情是,我的行是从字符串的第一部分抽象出一个数字。示例 26.50。我的线是带回 27。(将 26.50 从文本转换为数字)但是当我带回来时它四舍五入到 27。使用您的代码,它带回了 27.00。有没有更好的方法来做我所说的,所以它会带回 26.50。看起来它正在四舍五入,然后我将其转换为小数,所以我失去了变化?
    • @Matt:- 当您将其转换为数字时,它可能会进行舍入。所以我认为你需要在那里做出改变。让我编辑我的答案
    猜你喜欢
    • 2011-03-10
    • 1970-01-01
    • 2018-09-30
    • 2012-11-16
    • 1970-01-01
    • 2014-10-15
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多