我有一个查询返回记录状态列。记录状态列有几个值,如:“活动”,“已删除”等...
我需要按“Active”排序,然后“删除”,然后等......
我目前正在创建CTE以将每组记录带到UNION ALL。是否有更好的动态方式来完成查询?
谢谢,
答案 0 :(得分:5)
有关更多状态值,您可以执行以下操作:
WITH StatusOrders
AS
(
SELECT StatusOrderID, StatusName
FROM (VALUES(1, 'Active'),
(2, 'Deleted'),
...
n, 'last status')) AS Statuses(StatusOrderID, StatusName)
)
SELECT *
FROM YourTable t
INNER JOIN StatusOrders s ON t.StatusName = s.StatusName
ORDER BY s.StatusOrderID;
答案 1 :(得分:3)
您可以在此使用CASE
ORDER BY CASE WHEN Status = 'Active' THEN 0 ELSE 1 END ASC
但如果您有status
的更多值,并且想要对Active
进行排序,那么DELETE
ORDER BY CASE WHEN Status = 'Active' THEN 0
WHEN Status = 'Deleted' THEN 1
ELSE 2
END ASC
答案 2 :(得分:1)
WITH
cteRiskStatus
AS
(
SELECT RiskStatusID, RiskStatusName
FROM (VALUES(1, 'Active'),
(2, 'Draft'),
(3, 'Occured'),
(4, 'Escalated'),
(5, 'Closed'),
(6, 'Expired'),
(7, 'Deleted')) AS RiskStatuses(RiskStatusID, RiskStatusName)
)
SELECT * FROM cteRiskStatus
由于