错误:函数round(双精度,整数)不存在

问题描述 投票:0回答:4

我正在迁移一些已经在 MySQL 数据库中运行多年的查询,这些查询现在在 Postgres 中具有相同的结构。我被一个简单的圆形函数困住了,它以以下错误消息结束。

错误:函数round(双精度,整数)不存在

部分选择不起作用:

round(floor(pools.available_capacity_in_kb/1024/1024/1024*100)/100,2) as free,

pools.available_capacity_in_kb
在数据库中存储为 BIGINT (Postgres 10.9)

sql postgresql rounding postgres-10
4个回答
59
投票

我在地理坐标方面也遇到了同样的问题。经度是来自开放街道地图数据的双精度,需要一个圆形值。

我的解决方案工作正常:

select ROUND(CAST(longitude AS numeric),2) from my_points; 

35
投票

除了类型 CAST 语法之外,您还可以使用以下语法将一种类型的值转换为另一种类型

(cast :: operator)
:

select ROUND(value::numeric, 2) from table_x; 

请注意,带有强制转换运算符 (::) 的强制转换语法是 PostgreSQL 特定的,不符合 SQL 标准。


14
投票

问题的核心在其他地方。 PostgreSQL 对整数和 bigint 数字使用长除法(当除法的两个部分都是 int、bigint 值时)。所以

pools.available_capacity_in_kb/1024/1024/1024*100)/100
的结果是bigint。可能这不是您所期望的。

postgres=# \df round
                          List of functions
+------------+-------+------------------+---------------------+------+
|   Schema   | Name  | Result data type | Argument data types | Type |
+------------+-------+------------------+---------------------+------+
| pg_catalog | round | double precision | double precision    | func |
| pg_catalog | round | numeric          | numeric             | func |
| pg_catalog | round | numeric          | numeric, integer    | func |
+------------+-------+------------------+---------------------+------+
(3 rows)

round
没有任何
bigint
功能(因为它没有任何意义)。 请尝试使用浮点除法来修复它,例如

pools.available_capacity_in_kb/1024/1024/1024*100)/100.0

现在,结果将是

numeric
,并且函数
round(numeric, int)
存在 - 所以它应该可以工作。


2
投票

您也可以使用以下语法

select round((value::Decimal),2) from table_name;

请注意,带有强制转换运算符 (::) 的强制转换语法是 PostgreSQL 特定的,不符合 SQL 标准。

© www.soinside.com 2019 - 2024. All rights reserved.