gpt4 book ai didi

postgresql - Postgresql 四舍五入到小数点后两位

转载 作者:行者123 更新时间:2023-11-29 14:08:54 27 4
gpt4 key购买 nike

我试图在 Postgres SQL 中将除法和结果四舍五入到小数点后两位。我试过下面的方法,但它会将它们四舍五入为整数。

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

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

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

亲切的问候,JB78

最佳答案

假设 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

关于postgresql - Postgresql 四舍五入到小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52220166/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com