4

我有一个查询,其中返回一个记录状态列。记录状态列有几个值,例如:“活动”、“已删除”等...

我需要按“活动”排序结果,然后“删除”,然后等等......

我目前正在创建 CTE 以将每组记录带到 UNION ALL。是否有更好的动态方式来完成查询?

谢谢,

4

3 回答 3

6

对于更多状态值,您可以这样做:

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;
于 2013-02-05T08:24:00.813 回答
5

你可以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
于 2013-02-05T08:21:22.883 回答
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

谢谢

于 2013-02-05T08:48:45.180 回答