Solved

SQL Custom Sort Order

Posted on 2009-06-28
3
400 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
3 Comments
 
LVL 75

Accepted Solution

by:
Aneesh Retnakaran earned 500 total points
Comment Utility
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
Comment Utility
Fast and Acccurate.
0
 
LVL 17

Expert Comment

by:pssandhu
Comment Utility
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

In this article—a derivative of my DaytaBase.org blog post (http://daytabase.org/2011/06/18/what-week-is-it/)—I will explore a few different perspectives on which week today's date falls within using Microsoft SQL Server. First, to frame this stu…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

744 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now