【问题标题】:SQL Custom Sort BySQL 自定义排序依据
【发布时间】:2018-09-14 02:45:09
【问题描述】:

假设我在一个专栏中有这个:

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

我希望数据被排序并看起来像这样:

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

这可能吗?

【问题讨论】:

  • 添加一个新列,其中包含由您的规则生成的订单号。没有其他方法。
  • 这个排序的逻辑是什么?请参阅上面的评论。
  • 我有一些数据,只是为了美观,我想要一个特定的行在每一行之上,就是这样。

标签: sql-server tsql sql-server-2008-r2


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    相关资源
    最近更新 更多