TSQL Order By - List of hardcoded values
I have a query that returns among others the "Record Status" column. The record status column has several meanings, such as "Active", "Deleted", and so on.
I need to order results with "Active", then "Deleted", then etc.
I am currently creating a CTE to cast each recordset and then UNION ALL. Is there a better and dynamic way to get the request?
Thank,
+3
source to share
3 answers
For more status values, you can do this:
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;
+5
source to share