2012-06-02 32 views
0

嗨我有DB2中正在工作的SQL语句。ORDER BY CASE不起作用?

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 

我的查询不起作用。 有人可以告诉我如何解决这个问题吗? 感谢

+1

什么是错误?记住ORDER BY 1意味着第一列的顺序,并且您只有2列.... –

回答

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 
+0

中的CASE相同这工作感谢 – Dejan

+0

一个小问题 - 你知道也许我可以改变IN_PROGRESS进展中?因为我的查询中也有IN_PROGRESS – Dejan

+0

@dejan:是“in_progress”列还是列值? –

0

你好尝试,如果我没有记错

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

整理 年底为FIELD_NAME

+0

为了完整性,您还可以在案例中添加一个else,当然 – Botond

+2

与问题 –

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 
+0

这不是解决方案,因为它会在表格中显示为1-IN等,这当然不是我想要的东西 – Dejan