SQL自定义排序依据

问题描述 投票:0回答:2

假设我在列中有这个:

'a'
'b'
'c'
'd'
'e'

我想要对数据进行排序,看起来像这样:

'a'
'b'
'd'
'e'
'c'

这可能吗?

sql-server tsql sql-server-2008-r2
2个回答
2
投票
select letter
from letters
order by
   case letter
     when 'a' then 0
     when 'b' then 1
     when 'd' then 2
     when 'e' then 3
     when 'c' then 4
   end

2
投票

使用CASE语句的另一种方法是,

询问

select [column_name] 
from [your_table_name]
order by 
  case [column_name] 
  when 'c' then 2 
  else 1 end, 
[column_name];

Find a demo here

© www.soinside.com 2019 - 2024. All rights reserved.