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

Phr*_*ogz 32 sql postgresql syntax

我有一个Postgres表,其中包含一个带有数值的字符串列.我需要将这些字符串转换为数字的数字,但我需要将两个NULL值以及空字符串解释为0.

我可以将空字符串转换为空值:

# select nullif('','');
 nullif 
--------

(1 row)
Run Code Online (Sandbox Code Playgroud)

我可以将null值转换为0:

# select coalesce(NULL,0);
 coalesce 
----------
        0
(1 row)
Run Code Online (Sandbox Code Playgroud)

我可以将字符串转换为数字:

# select cast('3' as float);
 float8 
--------
      3
(1 row)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试结合这些技术时,我会遇到错误:

# 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;
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Phr*_*ogz 35

价值类型需要保持一致; 合并空字符串为0意味着你不能那么它比较nullnullif.所以这些工作之一:

# 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)
Run Code Online (Sandbox Code Playgroud)


mu *_*ort 9

你也可以用

cast(
    case
        when coalesce(orig, '') = '' then '0'
        else orig
    end
    as float
)
Run Code Online (Sandbox Code Playgroud)

你也可以解开那个,因为你开始相当冗长:

cast(
    case
        when orig is null then '0'
        when orig = '' then '0'
        else orig
    end
    as float
)
Run Code Online (Sandbox Code Playgroud)

或者你可以把演员阵容放在CASE中:

case
    when coalesce(orig, '') = '' then 0.0
    else cast(orig as float)
end
Run Code Online (Sandbox Code Playgroud)

CASE使得更容易考虑任何其他特殊条件,这似乎更清楚地表达了逻辑IMO.OTOH,个人品味等等.


小智 5

实际上,你可以将NULL转换为int,你只是不能将空字符串转换为int.假设如果data1包含空字符串或NULL,则在新列中需要NULL,您可以执行以下操作:

UPDATE table SET data2 = cast(nullif(data1, '') AS int);
Run Code Online (Sandbox Code Playgroud)

要么

UPDATE table SET data2 = nullif(data1, '')::int;
Run Code Online (Sandbox Code Playgroud)

参考