我想按字符串列排序,其中该列是枚举。例如:
+----+--------+----------------------+
| ID | NAME | STATUS |
+----+--------+----------------------+
| 1 | Serdar | ACTIVE |
| 2 | John | DEACTIVE |
| 3 | Jerry | WAITING_FOR_APPROVAL |
| 4 | Jessie | REJECTED |
+----+--------+----------------------+
我想按STATUS
订购。它应该对结果进行排序,使得第一个结果必须具有STATUS = WAITING_FOR_APPROVAL,然后是ACTIVE,然后是DEACTIVE,然后是REJECTED。
在SQL中有没有办法做到这一点?在java中有比较像Comparator的东西吗?
答案 0 :(得分:5)
您可以枚举CASE
语句中的值并按该
SELECT id, name, status
FROM your_table
ORDER BY (CASE status
WHEN 'WAITING_FOR_APPROVAL' THEN 1
WHEN 'ACTIVE' THEN 2
WHEN 'DEACTIVE' THEN 3
WHEN 'REJECTED' THEN 4
ELSE 5
END)