根据行结果desc在case中排序

时间:2016-09-24 11:58:50

标签: mysql

现在,当我运行查询时,它不会将最终的Score列从最高到最低排序。我似乎无法弄清楚如何把它放在我的情况下。我至少需要第一个和第二个案例来排序最后一列。

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.Address LIKE '%VINTAGE PARK LN' THEN 1
    WHEN locateparsed.Address LIKE '%SHADOW RIDGE LN' THEN 2
    WHEN list.Section = 'Sec. 1' AND list.Subdivision = 'Shadow Ridge' THEN 3
    WHEN list.Subdivision = 'Shadow Ridge' THEN 4
    WHEN locateparsed.KeyMap = '612P' THEN 5
    WHEN locateparsed.KeyMap = '612' THEN 6
    ELSE 7
END

输出示例我需要:

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

1 个答案:

答案 0 :(得分:0)

我认为你只需要包含score作为第二个排序键:

ORDER BY (CASE WHEN list.Address LIKE '%VINTAGE PARK LN' THEN 1
               WHEN locateparsed.Address LIKE '%SHADOW RIDGE LN' THEN 2
               WHEN list.Section = 'Sec. 1' AND list.Subdivision = 'Shadow Ridge' THEN 3
               WHEN list.Subdivision = 'Shadow Ridge' THEN 4
               WHEN locateparsed.KeyMap = '612P' THEN 5
               ELSE 7
          END),
         score DESC

这会将score的所有组排序为第二个键。如果您对前两个组特别需要这个,那么您需要为CASE排序添加第二个score