postgresql删除尾随零

时间:2017-03-10 14:53:35

标签: sql postgresql

我的查询对我来说很麻烦。我想从结果中删除尾随零。

Remove trailing zeros from decimal in SQL Server

Remove trailing zeroes using 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%?

2 个答案:

答案 0 :(得分:3)

不需要多次演员表,只需在结果上使用to_char()

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

答案 1 :(得分:1)

对于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<>fiddle demo