Mam tabelę Postgres z kolumną ciągów zawierających wartości numeryczne. Muszę przekonwertować te łańcuchy na liczby dla matematyki, ale potrzebuję zarówno wartości NULL
, jak i pustych ciągów, które będą interpretowane jako 0
.Rzucić ciąg na numer, interpretując pusty lub pusty łańcuch jako 0
mogę convert empty strings into null values:
# select nullif('','');
nullif
--------
(1 row)
i mogę convert null values into a 0
:
# select coalesce(NULL,0);
coalesce
----------
0
(1 row)
i mogę convert strings into numbers:
# select cast('3' as float);
float8
--------
3
(1 row)
Ale gdy próbuję połączyć te techniki, otrzymuję błędy:
# 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;
Co robię źle?
marginesie - jest lepiej w większości przypadków użyj 'numeric' zamiast' float'. Użyj 'float' tylko wtedy, gdy wiesz, że naprawdę potrzebujesz' float'. –