从数字中删除尾随零

问题描述 投票:0回答:4

我有一个查询,事实证明这对我来说很麻烦。我想从结果中删除尾随零。

在 SQL Server 中删除小数点后的零

使用sql删除尾随零

 select concat(100 * round(cast(count(ft.*) filter (where "Realtor_Sale" = 'Yes') 
as numeric(12,5)) / 
cast(count(ft.*) as numeric(12,5)),3),'%') as "Realtor Sales"

我得到的结果是:

84.800% --------------> I want 84.8%.

我也尝试这样做:

select concat(100 * round(cast(cast(count(ft.*) filter (where "Realtor_Sale" = 'Yes') 
as decimal(18,5)) as float) / 
cast(cast(count(ft.*) as decimal(18,5)) as float),3), '%') as "Realtor Sales"

错误:

ERROR:  function round(double precision, integer) does not exist
select round(cast(cast(count(ft.*) filter (where "Realtor_Sa...

如何将结果四舍五入到 84.8%?

sql postgresql
4个回答
4
投票

对于 PostgreSQL 13,只需调用 trim_scale 函数:

trim_scale(数字)→数字

通过删除尾随零来减小值的范围(小数小数位数)

trim_scale(8.4100) → 8.41

select trim_scale(100.0 * count(ft.*) filter (where "Realtor_Sale" = 'Yes')/ 
                  count(ft.*) ) ||'%'as "Realtor Sales"

db<>小提琴演示


3
投票

无需进行多次转换,只需在结果上使用

to_char()
即可:

select to_char((100 * count(ft.*) filter (where "Realtor_Sale" = 'Yes'))::decimal 
                / count(ft.*), 'FM99.0%') as "Realtor Sales"

0
投票

ROUND 函数的问题是,它还在整数值的末尾添加 0。

例如

select round(238,2)
--> 238.00

这是我尝试过的解决方案,它也保留了整数数据。

select cast(trim(trailing '0' from round(238.0100::numeric,2)::text)::numeric as text)

这将通过删除尾随空格来对值进行四舍五入,并保持整个数字不变。


0
投票

cast(round(投资金额,2) 为小数 (10,2))

© www.soinside.com 2019 - 2024. All rights reserved.