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

rad*_*cki 9 sql postgresql rounding postgres-10

我正在迁移一些查询,这些查询已经使用 MySQL 数据库运行了很长时间,现在在 Postgres 中具有相同的结构。我被简单的圆形函数卡住了,它以以下错误消息结尾。

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

select 的一部分不起作用:

round(floor(pools.available_capacity_in_kb/1024/1024/1024*100)/100,2) as free,
Run Code Online (Sandbox Code Playgroud)

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

fun*_*man 40

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

select ROUND(value::numeric, 2) from table_x; 
Run Code Online (Sandbox Code Playgroud)

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


Ger*_*erd 11

我对地理坐标有同样的问题。经度是来自开放街道地图数据的双精度值,需要一个粗略的值。

我的解决方案工作正常:

select ROUND(CAST(longitude AS numeric),2) from my_points; 
Run Code Online (Sandbox Code Playgroud)


Pav*_*ule 5

问题的核心在别处。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)
Run Code Online (Sandbox Code Playgroud)

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

pools.available_capacity_in_kb/1024/1024/1024*100)/100.0
Run Code Online (Sandbox Code Playgroud)

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