2016-09-23 115 views
0

我想按照匹配節,細分和關鍵映射的順序來整理我的結果。現在我得到了錯誤,但是我認爲我正處在正確的軌道上來完成這個任務。我無法弄清楚如何正確設置我的情況下按照這個順序。MySQL ORDER BY CASE不工作

編輯:

我已經更新了其運作的查詢,但它仍然沒有按照正確的順序排序。

SELECT 
    list.WorkOrder, 
    list.Address, 
    locateparsed.CrossStreet, 
    list.Section, 
    list.Subdivision, 
    locateparsed.KeyMap, 
    locateparsed.City, 
    list.Score 
FROM list 
LEFT JOIN locateparsed ON locateparsed.WorkOrder = list.WorkOrder 
    WHERE locateparsed.City = "PEARLAND" 
    AND list.Completed = 0 
    AND list.Reference = 0 
    AND locateparsed.Ticket IS NOT NULL 
GROUP BY list.WorkOrder 
ORDER BY CASE 
    WHEN list.Section = 'Sec. 1' THEN 1 
    WHEN list.Subdivision = 'Shadow Ridge' THEN 2 
    WHEN locateparsed.KeyMap = '612P' THEN 3 
END 

輸出例:

WO | Address | CrossStreet | Section | Subdivision | KeyMap | City 
1 | 123 test | other | Sec. 1 | Shadow Ridge | 612P | Pearland 
2 | 111 test | other | Sec. 1 | Shadow Ridge | 612P | Pearland 
3 | 333 other | bleach | Sec. 2 | Shadow Ridge | 612P | Pearland 
4 | 334 other | bleach | Sec. 2 | Shadow Ridge | 612P | Pearland 
5 | 848 other | bleach | Sec. 2 | Shadow Ridge | 612P | Pearland 
6 | 733 blah | random | Sec. 5 | Bright Ridge | 612P | Pearland 
7 | 722 hmm | blah | Sec. 5 | Bright Ridge | 612P | Pearland 
8 | 723 hmm | blah | Sec. 5 | Bright Ridge | 612P | Pearland 
9 | 111 asdf | fdas | Sec. 30 | Other Ridge | 650P | Pearland 
10 | 123 asdf | fdas | Sec. 30 | Other Ridge | 650P | Pearland 
+0

請添加示例數據和預期輸出 –

+1

您有語法錯誤。您不會在每個WHEN子句之後放置END,只是在CASE表達式的最後。 – Barmar

+0

CASE中沒有逗號 – Uueerdo

回答

1

你的語法是錯誤的。它應該是:

ORDER BY CASE 
    WHEN list.Section = 'Sec. 1' THEN 1 
    WHEN list.Subdivision = 'Shadow Ridge' THEN 2 
    WHEN locateparsed.KeyMap = '612P' THEN 3 
    ELSE 4 -- anything that doesn't match above conditions comes last 
END 

這裏有一個END整個CASE表達,每個WHEN後沒有了,WHEN子句之間沒有逗號。

+0

看到我的編輯,現在工作(不給錯誤),但它沒有正確排序。現在「第3節」在結果中首先出現 –

+0

在最後一次「WHEN THEN」之後,你需要類似'ELSE 9999999'的東西;目前任何結果行的情況下的值的值對於任何這些值爲空的情況都不爲真。 – Uueerdo

+0

這工作完美,我知道我很接近。謝謝! –