Question

SELECT TOP 1
        hol_id ,
        CONVERT(VARCHAR(12), hol_date, 112)
FROM    holiday
WHERE   hol_id = 5
UNION ALL
SELECT  hol_id ,
        CONVERT(VARCHAR(12), hol_date, 112)
FROM    holiday
WHERE   hol_id <> 5
ORDER BY CONVERT(VARCHAR(12), hol_date, 112) DESC

I see

1   20131218
5   20131018
6   20130818
3   20130405
4   20130311
2   20121129

I want to see

5   20131018
1   20131218
6   20130818
3   20130405
4   20130311
2   20121129
Was it helpful?

Solution

You should be ordering by actual date (hol_date) not by converted varchar value.

Assuming hol_id as Key column of the table (Not sure why you are using a TOP 1 here), try this query with ORDER BY CASE as below:

SELECT  hol_id ,
        CONVERT(VARCHAR(12), hol_date, 112)
FROM    holiday
ORDER BY CASE WHEN hol_id = 5 
              THEN DATEADD(year,100,getdate()) --Assuming 100 years as max
              ELSE hol_date 
         END DESC

OTHER TIPS

I would compute a new value to move a particular record to the top, as in:

order by
      case when hol_id = 5 then 0 else 1 end -- Sort hol_id 5 at the top
    , hol_date desc -- Sort the rest according to date
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top