postgresql Postgres sql四舍五入到小数点后2位

w41d8nur  于 2023-04-20  发布在  PostgreSQL
关注(0)|答案(2)|浏览(296)

我试图在PostgreSQL中将我的除法和结果四舍五入到小数点后2位。我已经尝试了下面的方法,但它将它们四舍五入到整数。

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

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

我怎样才能把结果四舍五入到小数点后两位?
亲切问候,JB78

dzhpxtsq

dzhpxtsq1#

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

kr98yfug2#

select round(*column_name*, 2) from table_name;

将在postgres中给予我们舍入到2个十进制值

相关问题