PostgreSQL:以单SQL语法顺序,根据从文本列计算出的数值 [英] PostgreSQL: IN A SINGLE SQL SYNTAX order by numeric value computed from a text column
本文介绍了PostgreSQL:以单SQL语法顺序,根据从文本列计算出的数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一列具有字符串值,例如 1/200, 3.5或 6。如何在单个SQL查询中将此字符串转换为数值?
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?
我的实际SQL更复杂,这是一个简单的示例:
My actual SQL is more complicated, here is a simple example:
SELECT number_value_in_string FROM table
number_value_in_string的格式将是以下格式之一:
number_value_in_string's format will be one of:
- ##
- #。##
- #/ ###
我需要按此列的数值排序。但是,当然,postgres不同意我认为1/200是正确的数字。
I need to sort by the numeric value of this column. But of course postgres doesn't agree with me that 1/200 is a proper number.
推荐答案
看到你的名字我只能发布您的答案的简化版本:
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;
忽略零除的可能性。
这篇关于PostgreSQL:以单SQL语法顺序,根据从文本列计算出的数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文