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

问题描述 投票:32回答:4

我有一个Postgres表,其中的字符串列带有数字值。我需要将这些字符串转换为数字以进行数学运算,但是我既需要NULL值,也需要将空字符串解释为0

我可以convert empty strings into null values

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

(1 row)

而且我可以convert null values into a 0

0

而且我可以# select coalesce(NULL,0); coalesce ---------- 0 (1 row)

convert strings into numbers

但是当我尝试结合使用这些技术时,会出现错误:

# select cast('3' as float);
 float8 
--------
      3
(1 row)

我在做什么错?

sql postgresql syntax
4个回答
35
投票

值的类型必须保持一致;将空字符串合并为0表示您无法将其与# 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; 中的null比较。所以这些作品之一:

nullif

9
投票

您也可以使用

# 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)

由于您一开始就相当冗长,您也可以将其解开一点:

cast(
    case
        when coalesce(orig, '') = '' then '0'
        else orig
    end
    as float
)

或者您可以将演员表放到案例中:

cast(
    case
        when orig is null then '0'
        when orig = '' then '0'
        else orig
    end
    as float
)

案例使解决任何其他特殊情况变得容易一些,这似乎也更清楚地表达了IMO逻辑。 OTOH,个人品味等等。


5
投票

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

case
    when coalesce(orig, '') = '' then 0.0
    else cast(orig as float)
end

UPDATE table SET data2 = cast(nullif(data1, '') AS int);

UPDATE table SET data2 = nullif(data1, '')::int;


0
投票

检查查询参数是否为空(接受null,空字符串或值):

Reference
© www.soinside.com 2019 - 2024. All rights reserved.