SQL 分区 ( / ) 在 postgresql 中没有给出我的答案

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34504497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:17:23  来源:igfitidea点击:

Division ( / ) not giving my answer in postgresql

sqlpostgresqldivisionmodulo

提问by zeewagon

I have a table softwareand columns in it as dev_cost, sell_cost. If dev_costis 16000 and sell_costis 7500.

我有一个表格software和其中的列dev_cost, sell_cost。如果dev_cost是 16000,sell_cost则是 7500。

How do I find the quantity of software to be sold in order to recover the dev_cost?

我如何找到要出售的软件数量以恢复dev_cost?

I have queried as below:

我查询如下:

select dev_cost / sell_cost from software ;

It is returning 2 as the answer. But we need to get 3, right?

它返回 2 作为答案。但是我们需要得到 3,对吧?

What would be the query for that? Thanks in advance.

对此的查询是什么?提前致谢。

回答by 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:

您的列具有整数类型,整数除法会将结果截断为零。要获得准确的结果,您需要将至少一个值转换为 float 或 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:

然后,您可以使用以下ceil()函数将结果四舍五入到最接近的整数:

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

(See demo on SQLFiddle.)

(请参阅SQLFiddle 上的演示。)

回答by Vivek S.

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

您可以将整数类型转换为numeric并使用ceil()函数来获得所需的输出

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

PostgreSQL ceil 函数返回大于或等于数字的最小整数值。

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

回答by AdagioDev

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:

您可以舍入您的 value ,并指定点后的位数:

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

回答by Abylay Sabirgaliyev

This query will round result to next integer

此查询会将结果四舍五入到下一个整数

select round(dev_cost ::decimal / sell_cost + 0.5)