postgresql Remove trailing zeroes

落爺英雄遲暮 提交于 2021-01-27 18:51:21

问题


I have a query which is proving to be cumbersome for me. I want to remove the trailing zeroes from the result.

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"

Result I am getting is:

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

I tried doing this as well:

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:

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

How do I get the result to round of to 84.8%?


回答1:


No need for the many casts, just use to_char() on the result:

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



回答2:


With PostgreSQL 13 it is matter of calling trim_scale function:

trim_scale ( numeric ) → numeric

Reduces the value's scale (number of fractional decimal digits) by removing trailing zeroes

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



来源:https://stackoverflow.com/questions/42721281/postgresql-remove-trailing-zeroes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!