Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

SQL Custom Sort Order

Posted on 2009-06-28
3
Medium Priority
?
424 Views
Last Modified: 2012-05-07
I have a table column 'STATUS' with the following possible Data.
STATUS
========
Active
Inactive
Cancelled
Closed
Pending

I want to Sort the table, but placing Closed on top, and Cancelled last, the other Status type should be Sorted by a Date column.

Is it possible to achieve this in SQL? I'm using SQL 2005.

SELECT * from TABLE_A ORDER BY (Closed on top, Cancelled below, others by Date)

0
Comment
Question by:dennisdominic
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 75

Accepted Solution

by:
Aneesh Retnakaran earned 2000 total points
ID: 24733339
SELECT * from TABLE_A
ORDER BY Case WHEN Status = 'Closed' then 99 WHEN 'Cancelled' THEN -99 Else 0 END DESC,[Date]


0
 
LVL 1

Author Closing Comment

by:dennisdominic
ID: 31597776
Fast and Acccurate.
0
 
LVL 17

Expert Comment

by:pssandhu
ID: 24733352
I am assumin you have data column, so you can do something like this:
Select *, CASE WHEN Status = 'Closed' Then Cast('1700-01-01' as Datetime)
                           WHEN Status = 'Cancelled' Then Cast('3000-01-01' as Datetime)
                           ELSE DateCol
                END as SortOrder
From Table_A
Order by CASE WHEN Status = 'Closed' Then Cast('1700-01-01' as Datetime)
                           WHEN Status = 'Cancelled' Then Cast('3000-01-01' as Datetime)
                           ELSE DateCol
                END


0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Ready to get certified? Check out some courses that help you prepare for third-party exams.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how the fundamental information of how to create a table.

604 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question