具有明确顺序的Order子句

时间:2019-04-06 02:24:42

标签: sql postgresql sqlalchemy sql-order-by

我一行有三个可能的结果

no 
neutral
yes

我想保留此订单。 DescASC不匹配。因此,有什么方法可以指定期望的顺序?

不确定是否相关,但是我正在使用sql alchemy。

.order_by(Survey.rating).all()      

3 个答案:

答案 0 :(得分:2)

对于Postgres中的这种类型的逻辑,数组可以很方便。一种方法是:

array_position(array['no', 'neutral', 'yes'], colname)

这很方便,因为它很容易扩展为更多值。

答案 1 :(得分:1)

在没有自然序列的情况下,您可以使用case表达式来控制排序。

order by case col1 when 'no' then 1 when 'neutral' then 2 else 3 end

答案 2 :(得分:0)

对于sqlalchemy API,我们可以使用'func'

from sqlalchemy import func

.order_by(func.array_position(array['no', 'neutral', 'yes'], colname) ) 

但是我们还应该检查colname的类型转换,b / c我们需要显式指示元素的数据类型(为此,sqlalchemy具有函数cast)。

然后指示类型,我们将得到以下内容:

from sqlalchemy import cast, Text

.order_by(func.array_position(array['no', 'neutral', 'yes'], cast(table.c.colname, Text)) )