用一些优先行自定义'order by'?

时间:2013-09-20 17:46:41

标签: sql sqlite

我在表格中有以下数据

pk | i | val
------------
1  | 0 | hi
2  | 3 | good bye
3  | 4 | good day
5  | 6 | howdy

如果我select * from mytable ORDER BY val,我会收到订单2,3,1,5。

但是如果我想在其他正常排序的行之前给两个特定的行赋予“首选项”呢?让我们说val = hi,再见。

换句话说,我如何编写SQL查询以便能够返回1,5,2,3?

1 个答案:

答案 0 :(得分:2)

select *
from table1
order by case when val in ('hi', 'howdy') then 0 else 1 end, val

<强> sql fiddle demo

select *
from table1
order by
    case val
        when 'howdy' then 0
        when 'hi' then 1
        else 2
    end, val

或(更容易添加新变量)

select *
from table1
order by
    case val
        when 'howdy' then 2
        when 'hi' then 1
        else 0
    end desc, val