【发布时间】:2013-09-27 20:37:38
【问题描述】:
我有一个 Postgres 表,其中包含一个带有数值的字符串列。我需要将这些字符串转换为数字进行数学运算,但我需要将 NULL 值和空字符串都解释为 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。只有当你知道你真的需要float时才使用float。
标签: sql postgresql syntax