我有一个Postgres表格,其中包含一个带有数字值的字符串列。我需要将这些字符串转换为数学数字,但我需要NULL
值以及空字符串被解释为0
。将字符串转换为数字,将空字符串或空字符串解释为0
我可以convert empty strings into null values:
# select nullif('','');
nullif
--------
(1 row)
,我可以convert null values into a 0
:
# select coalesce(NULL,0);
coalesce
----------
0
(1 row)
,我可以convert strings into numbers:
# select cast('3' as float);
float8
--------
3
(1 row)
但是,当我尝试将这些技术结合起来,我得到错误:
# select cast(nullif(coalesce('',0), '') as float);
ERROR: invalid input syntax for integer: ""
LINE 1: select cast(nullif(coalesce('',0), '') as float);
# select coalesce(nullif('3',''),4) as hi;
ERROR: COALESCE types text and integer cannot be matched
LINE 1: select coalesce(nullif('3',''),4) as hi;
我在做什么错?
附注 - 这是更好地在大多数情况下,使用'numeric'而不是'float'。只有当你知道你真的需要'浮动'时才使用'浮动'。 –