我有一個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'。只有當你知道你真的需要'浮動'時才使用'浮動'。 –