sql浮点精度问题

dffbzjpn  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(403)

我有这样的水果

+------+------------+
     | fruit|fruit_number|
     +------+------------+
     | apple|          20|
     |orange|          33|
     |  pear|          27|
     | melon|          31|
     |  plum|           8|
     |banana|           4|
     +------+------------+

我想生成每行的百分比,但当我将百分比列相加时,我无法得到100%

select fruit, round(fruit_number/123*100,2) as cnt_percent 
    from fruit_df_sql
    order by cnt_percent desc

如果我把cnt d u percent列加起来,我会得到这个

+----------------+
    |sum(cnt_percent)|
    +----------------+
    |           99.99|
    +----------------+

不是100%。我想是因为除法和圆带来了浮点精度问题。请帮忙。谢谢。

t30tvxxf

t30tvxxf1#

试着四舍五入到0位小数。

select fruit, round(fruit_number/123*100,0) as cnt_percent 
from fruit_df_sql
order by cnt_percent desc;

相关问题