PostgreSQL: IN A SINGLE SQL SYNTAX order by numeric value computed from a text column

前端 未结 4 1809
花落未央
花落未央 2021-01-21 10:32

A column has a string values like \"1/200\", \"3.5\" or \"6\". How can I convert this String to numeric value in single SQL query?

My actual SQL is more complicated, h

4条回答
  •  北海茫月
    2021-01-21 11:21

    This postgres SQL does the trick:

    select (parts[1] :: decimal) / (parts[2] :: decimal) as quotient
    FROM (select regexp_split_to_array(number_value_in_string, '/') as parts from table) x
    

    Here's a test of this code:

    select (parts[1] :: decimal) / (parts[2] :: decimal) as quotient
    FROM (select regexp_split_to_array('1/200', '/') as parts) x
    

    Output:

    0.005
    

    Note that you would need to wrap this in a case statement to protect against divide-by-zero errors and/or array out of bounds issues etc if the column did not contain a forward slash

    Note also that you could do it without the inner select, but you would have to use regexp_split_to_array twice (once for each part) and you would probably incur a performance hit. Nevertheless, it may be easier to code in-line and just accept the small performance loss.

提交回复
热议问题