需求:两个整数相除,保留两位⼩数并四舍五⼊,完了转成百分⽐形式,即4/5=0.80=80%
1.两个整数相除:
idn_dw=> select 4/5; column---------- 0(1 row)
在sql运算中,\"/\"意思是相除取整,这样⼩数部分就会被舍去。
2.⽤cast将被除数转成⼩数
idn_dw=> select cast(4 as numeric)/5; column
------------------------ 0.80000000000000000000(1 row)
也可以简化:pg中\"::\"是转换的意思
idn_dw=> select 4::numeric/5; column
------------------------ 0.80000000000000000000(1 row)
3.四舍五⼊,保留两位⼩数
idn_dw=> select round(cast(4 as numeric)/5,2); round------- 0.80(1 row)
4.放⼤100,转成百分⽐形式
idn_dw=> select concat(round(4::numeric/5,2)*100,'%'); concat-------- 80.00%(1 row)
但是,⼩数部分不需要,调整⼀下顺序
idn_dw=> select concat(round(4::numeric/5*100),'%'); concat-------- 80%(1 row)
完事。
补充:使⽤postgresql的round()四舍五⼊函数报错
需求:
使⽤postgresql的round()四舍五⼊保留两位⼩数报错:
HINT: No function matches the given name and argument types. You might
解决⽅案:
使⽤cast函数将需要四舍五⼊的值转为 numeric,转为其他的类型可能会报错
⽰例:
round(cast(计算结果) as numeric), 2)
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。如有错误或未考虑完全的地⽅,望不吝赐教。
因篇幅问题不能全部显示,请点此查看更多更全内容