删除 PostgreSQL 中数字列的所有尾随零

Removing all the trailing zeroes of a numeric column in PostgreSQL

我有这个 table 属性,其中有一列 atomic_mass 类型为 NUMERIC(9,6):

 atomic_mass 
-------------
    1.008000
    4.002600
    6.940000
    9.012200
   10.810000
   12.011000
   14.007000
   15.999000
    1.000000
(9 rows)

所以我想删除该列的所有尾随零,例如 1.008、4.0026 等。 所以我尝试执行以下操作

UPDATE properties SET atomic_mass=trim(trailing '0' from atomic_mass::text)::numeric;

但它不起作用。我测试了 trim 功能,效果很好。如果我输入

SELECT trim(trailing '0' from atomic_mass::text)::numeric from properties

它returns

rtrim  
--------
  1.008
 4.0026
   6.94
 9.0122
  10.81
 12.011
 14.007
 15.999
      1

我想要的专栏。那么我在这里做错了什么? 我正在使用 PostgreSQL 12.9。

您已将列定义为 NUMERIC(9,6)。从这里 Numeric typesNUMERIC(precision, scale),其中 scale 是:

The scale of a numeric is the count of decimal digits in the fractional part, to the right of the decimal point.

因此 运行 trim 更新值不会有帮助,因为列定义 scale 将覆盖它。尾随零是格式问题,必须在输出时处理。

更新

鉴于您对此答案的评论中关于能够更改列类型的信息:

create table numeric_test (num_fld numeric, num6_fld numeric(9,6));
nsert into numeric_test values (12.011000, 12.011000), (4.002600, 4.002600), (1.000000, 1.000000);

select * from numeric_test ;
  num_fld  | num6_fld  
-----------+-----------
 12.011000 | 12.011000
  4.002600 |  4.002600
  1.000000 |  1.000000

update numeric_test set num_fld = trim(trailing '0' from num_fld::text)::numeric, num6_fld = trim(trailing '0' from num6_fld::text)::numeric ;

select * from numeric_test ;
 num_fld | num6_fld  
---------+-----------
  12.011 | 12.011000
  4.0026 |  4.002600
       1 |  1.000000

--
insert into numeric_test values (9.012200, 9.012200);

select * from numeric_test ;
 num_fld  | num6_fld  
----------+-----------
   12.011 | 12.011000
   4.0026 |  4.002600
        1 |  1.000000
 9.012200 |  9.012200

使用不受约束的 numeric,您可以在更新 trim 时从现有值中删除尾随零。但是,如果它们包含在不包含 trim 它们的插入或更新中,您仍然会得到它们。