舍入数值

时间:2015-04-01 07:27:46

标签: sql postgresql aggregate-functions rounding

我想要对两列的值进行舍入:

select a.region as "Regions",
       a.suminsured,2 as "SumInsured" ,
       a.suminsured/b.sum*100 as pct 
from (
    SELECT  region, sum(suminsured) as suminsured 
    FROM "Exposure_commune" group by region
) a,
(select sum(suminsured) FROM "Exposure_commune") b

我希望suminsuredpct列带有2个小数位。有人能告诉我应该做些什么吗?

2 个答案:

答案 0 :(得分:0)

使用round() with two parameters,它仅适用于数据类型numeric

在此过程中,您的查询可以更简单,更快捷:

SELECT region
     , round(sum(suminsured), 2) AS suminsured
     , round((sum(suminsured) * 100) / sum(sum(suminsured)) OVER (), 2) AS pct 
FROM  "Exposure_commune"
GROUP  BY 1;

你可以使用sum()作为窗口函数来获得总数而不需要额外的子查询,这样更便宜。相关:

首先乘法通常更便宜,更准确(尽管numeric几乎不重要。)

数据类型不是numeric

对于数据类型双精度的真实 你可以......

  • 只是转换为numeric以使用相同的功能。
  • 乘以100,投放到integer并除以100.0
  • 乘以100并使用简单的round()并使用100

只有一个参数的简单round()也适用于浮点类型。

展示所有三种变体:

SELECT region
     , round(sum(suminsured), 2) AS suminsured
     , (sum(suminsured) * 100)::int / 100.0 AS suminsured2
     , round(sum(suminsured) * 100) / 100 AS suminsured3
     , round((sum(suminsured) * 100) / sum(sum(suminsured)) OVER (), 2) AS pct 
     , ((sum(suminsured) * 10000) / sum(sum(suminsured)) OVER ())::int / 100.0 AS pct2
     , round((sum(suminsured) * 10000) / sum(sum(suminsured)) OVER ()) / 100 AS pct3
FROM  "Exposure_commune"
GROUP  BY 1;

SQL Fiddle.

答案 1 :(得分:0)

您可以直接使用带有两个参数的数字。舍入十进制的第二个参数。

select sum(column_name::numeric(10,2)) from tablename