2013-09-23 30 views
22

数値を含む文字列を持つPostgresテーブルがあります。私はこれらの文字列を数学のための数に変換する必要がありますが、NULL値と空文字列の両方が0と解釈される必要があります。文字列を数値にキャストし、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; 

私は間違っていますか?

+3

サイドノート:DATA1は、空の文字列またはNULLが含まれている場合は、新しい列にNULLたいと仮定すると、あなたはこのような何かを行うことができますほとんどの場合、 'float'の代わりに' numeric'を使います。 'float'が本当に必要であることを知っているときだけ、' float'を使います。 –

答えて

22

値の型は一貫している必要があります。空の文字列を0に集約すると、の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) 
6

また、あなたはとにかくかなり冗長始めているので、あなたはその少しもアンラップでき

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 
) 

かでしたキャストをケースの中に入れます:

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

ケースでは、他の特別な条件を説明するのが少し楽になりますが、これは論理IMOのより明確な表現のようです。 OTOH、個人的な味とすべて。

3

実際には、NULLをintにキャストできます。空の文字列をintにキャストすることはできません。 - それが優れている

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

または

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

Reference

+0

2番目の文から:_ "[...]空の文字列だけでなくNULL値も0として解釈する必要があります。" _ – Phrogz

関連する問題