Division ( / ) not giving my answer in postgresql

痞子三分冷 提交于 2019-12-02 21:37:05
Ilmari Karonen

Your columns have integer types, and integer division truncates the result towards zero. To get an accurate result, you'll need to cast at least one of the values to float or decimal:

select cast(dev_cost as decimal) / sell_cost from software ;

or just:

select dev_cost::decimal / sell_cost from software ;

You can then round the result up to the nearest integer using the ceil() function:

select ceil(dev_cost::decimal / sell_cost) from software ;

(See demo on SQLFiddle.)

You can cast integer type to numeric and use ceil() function to get the desired output

The PostgreSQL ceil function returns the smallest integer value that is greater than or equal to a number.

SELECT 16000::NUMERIC / 7500 col 
      ,ceil(16000::NUMERIC / 7500) 

Result:

col                  ceil 
------------------   ---- 
2.1333333333333333     3    

So your query should be

select ceil(dev_cost::numeric/sell_cost) 
from software

You can also cast your variable to the desired type, then apply division:

 SELECT (dev_cost::numeric/sell_cost::numeric);

You can round your value , and specify the number of digits after point:

SELECT TRUNC((dev_cost::numeric/sell_cost::numeric),2);

This query will round result to next integer

select round(dev_cost ::decimal / sell_cost + 0.5)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!