sql—如何使列不显示0作为十进制,而应显示除0以外的十进制

f2uvfpb9  于 2021-07-13  发布在  Hive
关注(0)|答案(4)|浏览(356)

考虑一个同时包含十进制数和非十进制数的列

col1 
    98
    99.0
    66.2 
    99.6
    76

应为后转换函数

col1 
    98
    99
    66.2 
    99.6
    76

我试着按你说的做

select cast(col1 as decimal)
lf5gs5x2

lf5gs5x21#

使用 regexp_replace(col1,'\\.0+$','') --匹配。从字面上看,任何数量的零在字符串的结尾。
演示:

with mytable as (
select  
stack(5,'98',
        '99.0',
        '66.2',
        '99.6',
        '76') as col1 
)

select regexp_replace(col1,'\\.0+$','') as col1 from mytable;

结果:

col1
98
99
66.2
99.6
76

但它会留下这样的价值观 66.20 照原样。如果要同时删除不重要的尾随零: 66.20 --> 66.2 以及 66.60200 --> 66.602 , 66.0 --> 66 然后离开 600 按原样使用:

regexp_replace(regexp_replace(col1,'\\.0+$',''),'(\\d+\\.\\d+?)0+$','$1')
mpbci0fu

mpbci0fu2#

你可以用 case when 做这个。但是,由于您喜欢的显示格式,结果列将是字符串类型。

select 
    case when round(col1, 0) = col1 
         then cast(cast(round(col1, 0) as int) as string)
         else cast(col1 as string)
    end
from mytable
xmakbtuz

xmakbtuz3#

你试过float数据类型吗?

select cast(99.0 as float)
vptzau2j

vptzau2j4#

如果要控制格式,需要将其转换为字符串。这通常是在应用程序级别完成的。但您也可以在数据库中执行此操作:

select replace(printf(col1, '%.1f', col1), '.0', '')

这将使用两个小数位格式化字符串。然后移除 '.0' 如果有。

相关问题