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

前端 未结 4 1856
花落未央
花落未央 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:08

    Seeing your name I cannot but post a simplification of your answer:

    SELECT id, number_value_in_string FROM table
     ORDER BY CASE WHEN substr(number_value_in_string,1,2) = '1/'
            THEN 1/substr(number_value_in_string,3)::numeric 
            ELSE number_value_in_string::numeric END, id;
    

    Ignoring possible divide by zero.

提交回复
热议问题