微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我使用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您不希望任何带前导空格的填充。

原文地址:https://www.jb51.cc/postgresql/193772.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐