【问题标题】:Rounding of the numeric values数值的四舍五入
【发布时间】:2015-04-01 07:27:45
【问题描述】:

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

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

我希望 suminsured 和 pct 列带有 2 位小数。谁能告诉我该怎么做?

【问题讨论】:

  • 使用函数round,例如:round(a.suminsured,2) as "SumInsured"
  • 数据类型是必不可少的。 suminsured 是否定义为 numeric?表定义(psql 中的\d tbl)将阐明一切

标签: sql postgresql aggregate-functions rounding


【解决方案1】:

您可以直接使用带两个参数的数字。小数点的第二个参数。

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

【讨论】:

    【解决方案2】:

    使用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.

    【讨论】:

    • 感谢您的帮助,但它对我不起作用..我已经尝试过,但它抛出错误函数 round(double precision, integer) 不存在
    • @preeti:好吧,首先在问题中提供您的 Postgres 版本和表定义。它肯定在现代 Postgres 中工作,我添加了一个演示。啊.. 双精度 ...你看到我提到仅适用于数据类型数字的部分了吗?你有没有看到我要求数据类型的评论?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多