简体   繁体   中英

Order by and case in select query

users
id | status | qualified
1  | yes    | BE
2  | no     | BCOM
3  | no     | BSC
4  | no     | BE
5  | yes    | BE

I want users with qualified = BE to fetch first then with status yes then other users

I have written query as follows but not getting result as expected

SELECT * 
FROM users 
ORDER BY 
CASE WHEN qualified =  'BE'
THEN 0
 WHEN status =  'yes'
THEN 0  
ELSE 1 
END

In MySQL comparing results in 0 and 1 . So you can do

SELECT * 
FROM users 
ORDER BY qualified <> 'BE',
         status <>  'yes'

and generally you could do

SELECT * 
FROM users 
ORDER BY case when qualified = 'BE' then 1 else 2 end,
         case when status = 'yes' then 1 else 2 end

You can also do something like

select case when qualified = 'BE' Then 1 When status = 'Yes' then 2 else 3 End as Ranking, * from users order by Ranking

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM