JB7*_*B78 3 postgresql rounding
我试图在 Postgres SQL 中将除法和结果四舍五入到小数点后两位。我已经尝试了下面的方法,但它会将它们四舍五入为整数。
round((total_sales / total_customers)::numeric,2) as SPC,
round((total_sales / total_orders)::numeric,2) as AOV
Run Code Online (Sandbox Code Playgroud)
请问如何将结果四舍五入到小数点后两位?
亲切的问候, JB78
a_h*_*ame 11
假设 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
Run Code Online (Sandbox Code Playgroud)
例子:
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;
Run Code Online (Sandbox Code Playgroud)
返回:
round(total_sales / total_orders::numeric, 2) as SPC,
round(total_sales / total_orders::numeric, 2) as AOV
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14968 次 |
| 最近记录: |