Skip to content
Advertisement

How order by case and order too?

i have a query for my next table

|id |Name|type      |
---------------------
|1  |B   |Secondary |
|2  |A   |Scholar   |
|3  |C   |University|

This could be the sql query :

select * from invite order by  
        case "type" 
             when 'Scholar'   then 1 
             when 'Secondary' then 2
             when 'University' then 3
         end asc;

but now i need order by case: example: when 'Scholar' then 1 desc

its possible do that?

my goal is order by id, and by case type example:

|id |Name|type      |
---------------------
|1  |B   |Secondary |
|2  |B   |Secondary |
|3  |B   |Secondary |
|4  |A   |Scholar   |
|5  |A   |Scholar   |
|6  |C   |University|
|7  |A   |Scholar.  |

the result will be:

|id |Name|type      |
---------------------
|7  |A   |Scholar.  |
|5  |A   |Scholar   |
|4  |A   |Scholar   |
|3  |B   |Secondary |
|2  |B   |Secondary |
|1  |B   |Secondary |
|6  |C   |University|

Advertisement

Answer

Your question suggests that want a new direction within each group:

order by (case "type" 
             when 'Scholar'   then 1 
             when 'Secondary' then 2
             when 'University' then 3
          end) asc;
         (case when "type" = Scholar then id end) desc,
         id asc;

However, your example suggests that you just want a second order by key, id desc.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement