2017-05-04 58 views
2

我與排序由flag_color查詢工作,但顏色我希望它的優先級:如何按類型排序 - SQL

此查詢現在返回:

SELECT flag_color as color 
FROM  clinic_performance_flags 
GROUP BY clinic_user_id 
ORDER BY flag_color ASC 


green 
green 
green 
green 
red 
red 
red 
red 
yellow 
yellow 
yellow 

但是我想改變順序,所以順序變成(red應該永遠是第一個,yellow秒和​​第三個)示例:

red 
red 
red 
red 
yellow 
yellow 
yellow 
yellow 
green 
green 
green 
green 

回答

0

使用CASEORDER BY

SELECT flag_color as color 
FROM  clinic_performance_flags 
GROUP BY clinic_user_id 
ORDER BY CASE WHEN flag_color = 'red' THEN 1 
       WHEN flag_color = 'yellow' THEN 2 
       WHEN flag_color = 'green' THEN 3 
             ELSE 4 
     END, flag_color ASC 
0

使用FIELD函數。

SELECT flag_color AS color 
FROM clinic_performance_flags 
GROUP BY clinic_user_id 
ORDER BY FIELD(flag_color ,'red','yellow','green'), flag_color ASC 
0

你可以使用一個CASE語句

SELECT flag_color as color 
FROM  clinic_performance_flags 
GROUP BY clinic_user_id 
ORDER BY CASE WHEN flag_color = 'red' THEN 1 
       WHEN flag_color = 'yellow' THEN 2 
       WHEN flag_color = 'green' THEN 3 
       ELSE 4 END