基于作为另一列中的值存储的列进行排序

时间:2018-01-31 17:19:11

标签: sql postgresql dynamic-sql

我有这个要求 我的输入表:

select * from my_table order by (substring(sortorder,1))

所以我真正想要的是阅读' sortorder'列,以检查排序的标准是什么,然后排序我在那里找到的关键词。像

这样的东西
id,fi,serial

它只是一个例子。我知道查询没有意义。我想用select * from my_table order by id,fi,serial 替换我的order by子句所以当我在数据库上执行查询时,它将这些值作为列名并对其进行排序。像这样:

def startTornado():
    application = tornado.web.Application([
        (r"/", MainHandler),
    ])
    application.listen(80)
    tornado.ioloop.IOLoop.instance().start()
    print "Server is running"

def stopTornado():
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.add_callback(ioloop.stop)
    print "Asked Tornado to exit"

if __name__ == "__main__":
    #stopTornado()
    startTornado()

是否可能或有其他方法可以解决这个问题?

2 个答案:

答案 0 :(得分:0)

好的,我尝试了这个查询,但还没有彻底测试过,

{{1}}

我正在获得所需的输出,可以有人提供其他解决方案,我也想在程序中使用此查询(postgres中的函数)..我如何在查询中包装它。

答案 1 :(得分:0)

很丑,但在标准的SQL语法中,可以使用3x2联合。

select id as K1, fi as K2, serial as K3, *
from my_table
where sortorder = 'id,fi,serial'
union
select fi as K1, id as K2, serial as K3, *
from my_table
where sortorder = 'fi,id,serial'
union
...
order by K1, K2, K3

或类似

select (case sortorder
        when 'id,fi,serial' then id * 1000000 + fi * 1000 + serial
        when ...
        end) as K123, serial as K3, *
from my_table
order by K123