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

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

    I managed to solve my problem. Thanks all. It goes something like this, in a single SQL. (I'm using POSTGRESQL)

    It will sort a string coming in as either "#", "#.#" or "1/#"

    SELECT id, number_value_in_string FROM table ORDER BY CASE WHEN position('1/' in number_value_in_string) = 1 
        THEN 1/substring(number_value_in_string from (position('1/' in number_value_in_string) + 2) )::numeric 
        ELSE number_value_in_string::numeric 
    END ASC, id
    

    Hope this will help someone outhere in the future.

提交回复
热议问题