Cast string to number, interpreting null or empty string as 0

后端 未结 4 1086
情话喂你
情话喂你 2021-02-05 00:31

I have a Postgres table with a string column carrying numeric values. I need to convert these strings to numbers for math, but I need both NULL values as well as em

4条回答
  •  星月不相逢
    2021-02-05 00:43

    You could also use

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

    You could also unwrap that a bit since you're being fairly verbose anyway:

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

    or you could put the cast inside the CASE:

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

    A CASE makes it a bit easier to account for any other special conditions, this also seems like a clearer expression of the logic IMO. OTOH, personal taste and all that.

提交回复
热议问题