sql - 将字符串转换为数字,将 null 或空字符串解释为 0

标签 sql postgresql syntax

我有一个 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/

相关文章:

php - 我们应该始终绑定(bind)我们的 SQL 语句吗?

MySql Join with Sum 返回错误的输出

ruby-on-rails - 为什么 Rails 5 在模式文件中添加 nextval 方法?

postgresql - zsh : command not found: pg_dump on mac OS Big Sur

javascript - 为什么该代码返回 10 而不是 5?

C++ 继承 : Calling Base Class Constructor In Header

javascript - 检查任何 if 语句中是否使用了 Javascript 变量

mysql 将条目与下一个更高的值交换

c# - 在 LINQ 中对多个表进行分组

postgresql - 如何将csv数据导入postgres表