0

我有以下查询:

select 'junior' as type, value
from mytable
union
select 'intermediate' as type, value
from mytable
union
select 'senior' as type, value
from mytable

它返回以下数据:

type          value

Intermediate     10    
Junior            5
Senior            1

我只需要重新排序它看起来像这样

Junior          5
Intermediate   10        
Senior          1

我无法弄清楚使用哪个 order by 子句来实现按自定义特定值排序,我将如何实现这一点?

4

4 回答 4

2

我不知道您是否理解得很好,但我会再提取一列,例如带有整数值的“序列”。它将提供应用自定义订单的能力。

举个例子:

select results.type, results.value, results.sequence 
from (    
    select 'junior' as type, value, 0 as sequence
    from mytable
    union
    select 'intermediate' as type, value, 1 as sequence
    from mytable
    union
    select 'senior' as type, value, 2 as sequence
    from mytable
) as results order by results.sequence
于 2013-09-29T20:22:41.740 回答
2

您可以通过添加排序键列进行排序,也可以根据值添加简单的 case 语句。

-- Sort with Case statement
with sourceData as
(
  select 'junior' type, 5 value
  union all
  select 'intermediate' type, 10 value
  union all
  select 'senior' type, 1 value
)
select * 
from sourceData
order by 
  case type
    when 'junior' then 0
    when 'intermediate' then 1
    when 'senior' then 2
    else null
  end

用于测试的SQL Fiddle 。

于 2013-09-29T20:29:10.457 回答
1

您需要添加第三列,例如 sortorder。然后,为其分配适当的整数值,

select 'junior' as type, value, 1 as sortorder
from mytable
union
select 'intermediate' as type, value, 2 as sortorder
from mytable
union
select 'senior' as type, value, 3 as sortorder
from mytable
order by 3
于 2013-09-29T20:25:59.703 回答
0

试试这个。

select TYPE, value from (select type,value, row_number() over (order by type) as rowno from #mytable union select type, value, row_number() over (order by type) as rowno from #mytable union select type,value , row_number() over (order by type) as rowno from #mytable)a order by 2 desc

于 2013-09-30T06:31:38.940 回答