加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在PostgreSQL中将平均值舍入到小数点后两位?

发布时间:2020-12-13 16:52:10 所属栏目:百科 来源:网络整理
导读:我使用PostgreSQL通过Ruby宝石的续集。 我试图舍入到两个小数位。 这里是我的代码: SELECT ROUND(AVG(some_column),2) FROM table 我得到以下错误: PG::Error: ERROR: function round(double precision,integer) does not exist (Sequel::DatabaseError)
我使用PostgreSQL通过Ruby宝石的续集。

我试图舍入到两个小数位。

这里是我的代码:

SELECT ROUND(AVG(some_column),2)    
FROM table

我得到以下错误:

PG::Error: ERROR:  function round(double precision,integer) does 
not exist (Sequel::DatabaseError)

我得到没有错误,当我运行以下代码:

SELECT ROUND(AVG(some_column))
FROM table

有人知道我在做什么错了吗?

PostgreSQL没有定义round(双精度,整数)。由于@Catcall在注释中解释,需要精度的轮的版本仅可用于数字。
regress=> SELECT round( float8 '3.1415927',2 );
ERROR:  function round(double precision,integer) does not exist

regress=> df *round*
                           List of functions
   Schema   |  Name  | Result data type | Argument data types |  Type  
------------+--------+------------------+---------------------+--------
 pg_catalog | dround | double precision | double precision    | normal
 pg_catalog | round  | double precision | double precision    | normal
 pg_catalog | round  | numeric          | numeric             | normal
 pg_catalog | round  | numeric          | numeric,integer    | normal
(4 rows)

regress=> SELECT round( CAST(float8 '3.1415927' as numeric),2);
 round 
-------
  3.14
(1 row)

(在上面,注意float8只是双精度的速记别名。你可以看到PostgreSQL在输出中扩展它)。

您必须将值舍入为数字,以使用圆的双参数形式。只是append :: numeric用于速记转型,如round(val :: numeric,2)。

如果您要格式化为用户显示,请不要使用round。使用to_char(参见手册中的data type formatting functions),它允许您指定一种格式,并为您提供一个文本结果,不会受到客户端语言可能对数值的影响。例如:

regress=> SELECT to_char(float8 '3.1415927','FM999999999.00');
    to_char    
---------------
 3.14
(1 row)

to_char将为您舍入数字,作为格式化的一部分。 FM前缀告诉to_char您不希望任何带前导空格的填充。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读