Search code examples
sql-servert-sqlsql-server-2017

Custom order by in SQL Server


Below is the select statement

select * 
from #final
order by 
    case  
       when [Col1] in (select top 10 [Col1] from #take order by [Col2] desc) 
          then 0
          else 2
    end

My above select statement returns the result as below

            Col1                              Col2
            --------------------------------------
            App                              86748
            AppService                         832
            BK                               21227
            Cap                             160272
            Fukusima                          1634
            McBaa                             1727
            Others                            6718

However, I would like to get this result instead:

            Col1                              Col2
            --------------------------------------
            Cap                             160272
            App                              86748
            BK                               21227
            McBaa                             1727
            Fukusima                          1634
            AppService                         832
            Others                            6718

How to achieve this? Thanks.


Solution

  • You just differenced between the two types, but inside that type 0, there is no second order method. Just add then Col1 as second order, descending.

    select * from #final
            order by 
            case when [Col1] in (select top 10 [Col1] from #take order by [Col2] desc) then 0
            else 2
            end, [Col2] desc