2012-06-02 75 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