Rounding of the numeric values

梦想的初衷 提交于 2019-12-13 09:45:29

问题


I want to round of the values of two columns:

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

I want the suminsured and pct columns to come with 2 decimal places. Can someone tell me what I should do?


回答1:


Use round() with two parameters, which only works for the data type numeric.

While being at it, your query can be simpler and faster:

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;

You can use sum() as window function to get the total without additional subquery, which is cheaper. Related:

  • Postgres window function and group by exception

Multiplying first is typically cheaper and more exact (although that barely matters with numeric).

Data type is not numeric

For data types double precision of real You can ...

  • just cast to numeric to use the same function.
  • multiply by 100, cast to integer and divide by 100.0.
  • multiply by 100 and use the simple round() and devide by 100.

The simple round() with just one parameter works for floating point types as well.

Demonstrating all three variants:

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.




回答2:


You can use directly numeric with two parameters. Second parameter for round decimal.

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


来源:https://stackoverflow.com/questions/29385131/rounding-of-the-numeric-values

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