SQL 合并两个表 - Order BY
SQL Merge two tables - Order BY
我有一个数据table如下。
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
我需要得到如下结果table
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 park ,如果我合并所有这些 table 并执行 order通过 desc 得到结果 table。它将按 整体、第 1 周、第 2 周和第 3 周 排序。
但我需要按整体、第 3 周、第 2 周和第 1 周
订购
感谢您的回复。
谢谢
这里是使用 case 表达式来控制排序的选项。
order by case [Week]
when 'Overall' then 1
when 'Week3' then 2
when 'Week2' then 3
when 'Week1' then 4
end
您可以使用 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
声明更简单。
我有一个数据table如下。
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
我需要得到如下结果table
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 park ,如果我合并所有这些 table 并执行 order通过 desc 得到结果 table。它将按 整体、第 1 周、第 2 周和第 3 周 排序。
但我需要按整体、第 3 周、第 2 周和第 1 周
订购感谢您的回复。
谢谢
这里是使用 case 表达式来控制排序的选项。
order by case [Week]
when 'Overall' then 1
when 'Week3' then 2
when 'Week2' then 3
when 'Week1' then 4
end
您可以使用 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
声明更简单。