Postgres SQL四舍五入到小数点后两位

时间:2018-09-07 10:03:32

标签: postgresql rounding

我试图将除法求和结果四舍五入到Postgres SQL中的小数点后两位。我尝试了以下方法,但是将它们四舍五入为整数。

round((total_sales / total_customers)::numeric,2) as SPC,

round((total_sales / total_orders)::numeric,2) as AOV

如何将结果四舍五入到小数点后两位?

亲切的问候, JB78

1 个答案:

答案 0 :(得分:1)

假设total_sales和total_customers是integer列,则表达式total_sales / total_orders产生integer

在将它们四舍五入之前,您需要至少转换其中的一个 ,例如:total_sales / total_orders::numeric以便从除法得到小数点的结果:

round(total_sales / total_orders::numeric, 2) as SPC,
round(total_sales / total_orders::numeric, 2) as AOV

示例:

create table data
(
   total_sales integer,
   total_customers integer, 
   total_orders integer
);

insert into data values (97, 12, 7), (5000, 20, 30);

select total_sales / total_orders as int_result,
       total_sales / total_orders::numeric as numeric_result,
       round(total_sales / total_orders::numeric, 2) as SPC,
       round(total_sales / total_orders::numeric, 2) as AOV
from data;

返回:

int_result | numeric_result       | spc    | aov   
-----------+----------------------+--------+-------
        13 |  13.8571428571428571 |  13.86 |  13.86
       166 | 166.6666666666666667 | 166.67 | 166.67