SQL合并两个表 - Order BY

时间:2015-03-27 15:35:46

标签: sql sql-server database sql-order-by union-all

我有一个如下数据表。

Select * from TBL_01
Week     Group
Overall  Nicol  
Overall  Julie
Overall  Kelly
Select * from TBL_02
Week     Group
Week1    Nicol
Week1    Julie
Week1    Kelly
Week2    Nicol
Week2    Julie
Week2    Kelly
Week3    Nicol
Week3    Julie
Week3    Kelly

我需要获得如下所示的结果表

Week     Group
Overall  Nicol  
Overall  Julie
Overall  Kelly
Week3    Nicol
Week3    Julie
Week3    Kelly
Week2    Nicol
Week2    Julie
Week2    Kelly
Week1    Nicol
Week1    Julie
Week1    Kelly

这里的trickey公园是我需要一周,如果我联合所有这些表,并通过desc 按订购结果表。它将按整体,第1周,第2周和第3周排序。

但我需要按整体,第3周,第2周和第1周

订购

感谢您的回复。

谢谢

2 个答案:

答案 0 :(得分:2)

这是使用case表达式控制排序的选项。

order by case [Week] 
    when 'Overall' then 1
    when 'Week3' then 2
    when 'Week2' then 3
    when 'Week1' then 4
end

答案 1 :(得分:1)

您可以使用union all然后使用order by

select week, grp
from ((select week, grp from tbl_01) union all
      (select week, grp from tbl_02)
     ) t
order by charindex(week, 'Overall,Week3,Week2,Week1')

我发现charindex()为此目的比简单case声明更简单。