Solved

SQL Custom Sort Order

Posted on 2009-06-28
3
413 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 500 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

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

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

Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how the fundamental information of how to create a table.

724 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