需求:兩個(gè)整數(shù)相除,保留兩位小數(shù)并四舍五入,完了轉(zhuǎn)成百分比形式,即4/5=0.80=80%
1.兩個(gè)整數(shù)相除:
idn_dw=> select 4/5;
?column?
----------
0
(1 row)
在sql運(yùn)算中,"/"意思是相除取整,這樣小數(shù)部分就會(huì)被舍去。
2.用cast將被除數(shù)轉(zhuǎn)成小數(shù)
idn_dw=> select cast(4 as numeric)/5;
?column?
------------------------
0.80000000000000000000
(1 row)
也可以簡(jiǎn)化:pg中"::"是轉(zhuǎn)換的意思
idn_dw=> select 4::numeric/5;
?column?
------------------------
0.80000000000000000000
(1 row)
3.四舍五入,保留兩位小數(shù)
idn_dw=> select round(cast(4 as numeric)/5,2);
round
-------
0.80
(1 row)
4.放大100,轉(zhuǎn)成百分比形式
idn_dw=> select concat(round(4::numeric/5,2)*100,'%');
concat
--------
80.00%
(1 row)
但是,小數(shù)部分不需要,調(diào)整一下順序
idn_dw=> select concat(round(4::numeric/5*100),'%');
concat
--------
80%
(1 row)
完事。
補(bǔ)充:使用postgresql的round()四舍五入函數(shù)報(bào)錯(cuò)
需求:
使用postgresql的round()四舍五入保留兩位小數(shù)
報(bào)錯(cuò):
HINT: No function matches the given name and argument types. You might
解決方案:
使用cast函數(shù)將需要四舍五入的值轉(zhuǎn)為 numeric,轉(zhuǎn)為其他的類(lèi)型可能會(huì)報(bào)錯(cuò)
示例:
round(cast(計(jì)算結(jié)果) as numeric), 2)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- postgresql數(shù)據(jù)庫(kù)連接數(shù)和狀態(tài)查詢(xún)操作
- 解決postgresql 數(shù)據(jù)庫(kù) update更新慢的原因
- postgresql查詢(xún)自動(dòng)將大寫(xiě)的名稱(chēng)轉(zhuǎn)換為小寫(xiě)的案例
- 聊聊PostgreSql table和磁盤(pán)文件的映射關(guān)系
- PostgreSQL 中的單引號(hào)與雙引號(hào)用法說(shuō)明