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

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

    I would define a stored function to convert the string to a numeric value, more or less like this:

    CREATE OR REPLACE FUNCTION fraction_to_number(s CHARACTER VARYING)
    RETURN DOUBLE PRECISION AS
    BEGIN
       RETURN
       CASE WHEN s LIKE '%/%' THEN
           CAST(split_part(s, '/', 1) AS double_precision) 
           / CAST(split_part(s, '/', 2) AS double_precision)
       ELSE
           CAST(s AS DOUBLE PRECISION)
       END CASE
    END
    

    Then you can ORDER BY fraction_to_number(weird_column)

    If possible, I would revisit the data design. Is it all this complexity really necessary?

提交回复
热议问题