问题描述
考虑一个包含两列 RoleId 和 User Name 的示例表
Consider a Sample Table with two Column RoleId and User Name
Role | Name 1 AB 3 A 1 ABC 2 D 2 B 3 Abb 1 E 4 TE
如何使用 SQL 查询获得以下输出.
How can i use SQL queries to get following Output.
Role | Name 3 A 3 Abb 1 AB 1 ABC 1 E 2 B 2 D 4 TE
我只想先按角色 ID 3 排序,然后再按剩余的角色 ID 排序.目前我正在使用 Union 来实现//
I just want to Order by Role Id 3 first then by remaining Roleid. Currently i am using Union to achieve so //
SELECT * FROM (SELECT * From @temp Where roleid=3 UNION ALL SELECT * From @temp Where roleid != 3 ) as X
推荐答案
您可以使用 case 进行更复杂的排序:
You can use case to make more complex ordering:
select * from @temp order by case when Role = 3 then 0 else 1 end, Role, Name