首页 > 数据库 >pg数据库百分比处理

pg数据库百分比处理

时间:2022-11-06 15:46:57浏览次数:61  
标签:百分比 complete 数据库 numeric pg total round 除数 小数

参考声明:https://blog.csdn.net/magi1201/article/details/115719675

PostgreSQL数据库中,两个integer类型数据,如何处理为百分比形式

有表 student ,其中id字段为character类型,total和complete字段为integer型

img

total为总任务量,complete为完成任务量,当前诉求,求出完成率,保留一位小数

操作尝试

一,直接相除 complete/total,可以看到结果为0

img

这里为0,因为两个字段均为integer型,会按整数相除处理。

二,使用round函数 round(complete/total, 1)

img

这里结果与操作一类似,只是加了小数点。因为round只是对round(complete/total, 1)中输入的原值做格式化处理,而原值complete/total依然遵循两个integer数据相除的原则。

查看round后的结果列,结果值类型为 numeric,尝试将除数或被除数设置为numeric类型

三、除数小数化 complete::numeric,round(complete::numeric/total, 3)

img

这里的操作,将complete做了小数化,这里,可以同时将total做小数化,效果相同

四,百分比形式

如果要将结果展示为百分比形式,比如0.125要展示为12.5%

img

这里做了一个操作 round(complete*100::numeric/total, 1)||'%'

  • 除数complete 乘以 100
  • round小数保留3位修改为了*1*
  • round函数外拼接 *|| '%'*

五、除数为0处理

如果除数total有为0的情况,complete/total 会报错,使用case when 关键字

select complete, total,
(case when total=0 then '/' else round(complete*100::numeric/total, 1)||'%' end) as complete_rate
from student;

img

如此,除数为0的问题也成功解决。

标签:百分比,complete,数据库,numeric,pg,total,round,除数,小数
From: https://www.cnblogs.com/javaxubo/p/16862703.html

相关文章