【问题标题】:Converting a mixed fraction to a float number in Netezza在 Netezza 中将带分数转换为浮点数
【发布时间】:2015-08-17 04:20:21
【问题描述】:

我有一个数字以 3 种格式存储为文本的字段:

xx. (example: 31.)
xx.x (example: 31.2)
xx x/x (example: 31 2/7)

对于最终结果,我需要所有数字都是十进制格式(即 xx.x)。

将前两种格式转换为小数相当简单,但我还没有完全弄清楚如何转换最后一种情况,因为简单的 CAST 函数不起作用。我已经使用 INSTR 函数来隔离这些数字的所有小数情况,但我不知道从那里去哪里。我查看了其他示例,但某些引用的函数(如 SUBSTRING_INDEX)在 Netezza 中不存在。

【问题讨论】:

    标签: sql netezza


    【解决方案1】:

    我认为@Niederee 有蛮力的解决方案,但我会使用sql extensions toolkit

    create temporary table fractions (
      val nvarchar(64)
    ) distribute on random;
    
    insert into fractions values ('2.');
    insert into fractions values ('2.3');
    insert into fractions values ('31 2/7');
    insert into fractions values('2 0/8');
    insert into fractions values('516 56/537');
    
    select
      val
      ,case
        when regexp_like(val,'^[\d\.]+$') then val::numeric(20,10) --Cast it if we can.
        when regexp_like(val,'^[\d\.\s\/]+$')
          then regexp_extract(val,'\d+',1,1)::numeric(20,10) --Whole.
            + ( 
              regexp_extract(val,'\d+',1,2)::numeric(20,10) --Numerator.
              / regexp_extract(val,'\d+',1,3)::numeric(20,10) --Denominator.
            )
        else null
      end
    from
      fractions;
    

    【讨论】:

      【解决方案2】:

      尝试以下方法:

      create temp table so_test (
      txt_val varchar(100)
      );
      
      insert into so_test values ('31.');
      insert into so_test values ('31.2');
      insert into so_test values ('31 2/7');
      
      select txt_val
      , cast(decode(substr(txt_val,1,instr(txt_val,' ')),'',txt_val,substr(txt_val,1,instr(txt_val,' ')))  as numeric(18,2))  as root
      ,cast(substr(txt_val,instr(txt_val,' ')+1,length(txt_val)-instr(txt_val,'/')) as numeric(18,2))
      /cast(substr(txt_val,instr(txt_val,'/')+1,length(txt_val)) as numeric(18,2)) as fraction
      ,cast(root + case when fraction = 1 then 0 else fraction end as numeric(3,1)) as num_val
      
      from so_test
      

      【讨论】:

        【解决方案3】:

        感谢大家的帮助。我忘了关闭它,我实际上想出了一个方法:

        select
          case when instr(num,'/') > 0 then 
               cast(substr(num,1,2) as float) 
               + (cast(substr(num,4,1) as float)/cast(substr(num,6,1) as float))
          when instr(num,'.') > 0 then cast(substr(num,1,4) as float) 
          else cast(num as float)
        end as float_num
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-16
          • 2011-04-04
          • 1970-01-01
          • 2021-08-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多