手动指定查询顺序

时间:2015-11-17 09:19:46

标签: sql postgresql

我在PostgreSQL中有一个返回的查询:

id      operation   quantity   date
----------------------------------------
1282    WITHDRAW      20    2015-01-01
541     INCOMING      50    2015-01-01
4788    ACCEPT        17    2015-01-01
4789    ACCEPT        20    2015-01-01
.....

查询顺序按date ...

对记录进行排序

但是,我希望按operation执行二级订单:首先INCOMING,然后是ACCEPT,然后是WITHDRAW。同一操作的记录之间的顺序并不重要:

541     INCOMING      50    2015-01-01
4788    ACCEPT        17    2015-01-01
4789    ACCEPT        20    2015-01-01
1282    WITHDRAW      20    2015-01-01

541     INCOMING      50    2015-01-01
4789    ACCEPT        20    2015-01-01
4788    ACCEPT        17    2015-01-01
1282    WITHDRAW      20    2015-01-01

都好。

我无法使用operation列或id列,因为它无法提供所需的结果......

Select ...
from ...
where ...
order by date

如何手动指定我想要的订单..?

我正在寻找类似的SQL语法:

order by date, (operation order by: INCOMING,ACCEPT,WITHDRAW) 

2 个答案:

答案 0 :(得分:4)

通过以下方式为订单使用表达式:

order by date, 
         case operation 
              when 'INCOMING' then 1
              when 'ACCEPT' then 2
              when 'WITHDRAW' then 3
              else 4 -- this is a fallback, anything else will be sorted at the end
         end 

答案 1 :(得分:0)

从Postgres v9.5开始,可以使用Nicer解决方案。

ORDER BY date, 
     array_position(ARRAY['INCOMING', 'ACCEPT', 'WITHDRAW']::varchar[], operation)