我有一个Postgres表,带有一个带数字值的字符串列。我需要将这些字符串转换为数字以进行数学运算,但我需要同时使用两个NULL值和空字符串来将其解释为0。
NULL
0
我可以将空字符串转换为null值:
# select nullif('',''); nullif -------- (1 row)
而且我可以将空值转换为0:
# select coalesce(NULL,0); coalesce ---------- 0 (1 row)
而且我可以将字符串转换为数字:
# 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;
我究竟做错了什么?
值的类型必须保持一致;将空字符串合并为0表示您无法再将其与null中的进行比较nullif。因此,这些作品之一:
null
nullif
# create table tests (orig varchar); CREATE TABLE # insert into tests (orig) values ('1'), (''), (NULL), ('0'); INSERT 0 4 # select orig, cast(coalesce(nullif(orig,''),'0') as float) as result from tests; orig | result ------+-------- 1 | 1 | 0 | 0 0 | 0 (4 rows) # select orig, coalesce(cast(nullif(orig,'') as float),0) as result from tests; orig | result ------+-------- 1 | 1 | 0 | 0 0 | 0 (4 rows)