【问题标题】:ERROR: function round(double precision, integer) does not exist错误:函数round(双精度,整数)不存在
【发布时间】:2020-03-03 00:58:54
【问题描述】:

我正在迁移一些已经使用 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


    【解决方案1】:

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

    我的解决方案工作正常:

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

    【讨论】:

    • 当我在 db-fiddle 中使用 Postgres 9.6 时遇到问题时,该解决方案对我有用
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      问题的核心在其他地方。 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)
      

      bigint 没有任何round 函数(因为它没有任何意义)。 请尝试使用浮点除法修复它

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

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

      【讨论】:

      • 函数序列 "round(floor( ..." 不是必需的,并且无论如何都不会生成。floor 函数返回 "最大的 integer 小于或等于参数”,你不能四舍五入一个整数 - 至少不能没有 UDF。
      • 非常感谢 Pavel 的快速周转。你是对的 - round 函数不适用于 bigint。我将数据类型更改为数字,效果很好。 round(floor(pools.available_capacity_in_kb::numeric/1024/1024/1024*100)/100,2) 免费,
      • @radeklopatecki 请关闭此任务
      猜你喜欢
      • 1970-01-01
      • 2019-12-02
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 2017-06-21
      • 1970-01-01
      相关资源
      最近更新 更多