我有一个 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;
我做错了什么?
最佳答案
值的类型需要保持一致;将空字符串合并为 0 意味着您无法将它与 nullif
中的 null
进行比较。所以这些作品中的任何一个:
# 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)
关于sql - 将字符串转换为数字,将 null 或空字符串解释为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18950951/