问题
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