ORDER BY CASE不起作用?

时间:2012-06-02 22:26:43

标签: sql db2 sql-order-by

您好我在DB2中有SQL语句正在运行。

select  distinct 'IN' as STATUS,
    (select count(*) from table.......)
from table

UNION ALL

select  distinct 'OUT',
   (select count(*) from table.......)
from table

UNION ALL

select  distinct 'FINISHED',
   (select count(*) from table.......)
from table

order by status

但如果我将最后一行改为

order by 
 case STATUS
 when 'IN' then 1
 when 'OUT' then 2
 when 'FINISHED' then 3
end

我的查询不起作用。 谁能告诉我如何解决这个问题? 感谢

3 个答案:

答案 0 :(得分:3)

尝试将UNION包装到派生表中并对其进行排序:

select *
from ( 
   .... here goes your statement ...
) t
order by 
   case STATUS
      when 'IN' then 1
      when 'OUT' then 2
      when 'FINISHED' then 3
   end

答案 1 :(得分:1)

您可以随时将排序#添加到状态:

select  distinct '1-IN' as STATUS,
    (select count(*) from table.......)
from table

UNION ALL

select  distinct '2-OUT',
   (select count(*) from table.......)
from table

UNION ALL

select  distinct '3-FINISHED',
   (select count(*) from table.......)
from table

order by status

答案 2 :(得分:0)

你好试试这个应该有用,如果我没记错的话

    order by 
     case 
      when STATUS='IN' then 1
      when STATUS='OUT' then 2
      when STATUS='FINISHED' then 3
     end

你也可以在完成时命名 以field_name结尾