Sql server联合但保持顺序

时间:2014-01-17 09:00:36

标签: sql-server

有没有办法合并两个表,但是保持第一个表中的行首先出现在结果集中?

例如:

表1

name        surname
-------------------
John         Doe
Bob          Marley
Ras          Tafari

表2

name       surname
------------------
Lucky      Dube
Abby       Arnold

我希望结果集为:

name        surname
-------------------
John         Doe
Bob          Marley 
Ras          Tafari
Lucky      Dube
Abby       Arnold

不幸的是,工会以某种方式重新排序表。有办法解决这个问题吗?

4 个答案:

答案 0 :(得分:40)

试试这个: -

Select * 
from
( 
Select name,surname, 1 as filter
from  Table1
Union all
Select name,surname , 2 as filter
from Table2
)
order by filter

答案 1 :(得分:12)

保证输出顺序的唯一方法是使用ORDER BY

SELECT name,surname,1 as rs
FROM table1
UNION ALL
SELECT name,surname,2
FROM table2
ORDER BY rs

如果您不希望rs出现在最终结果集中,请将UNION作为子查询执行:

SELECT name,surname
FROM (
  SELECT name,surname,1 as rs
  FROM table1
  UNION ALL
  SELECT name,surname,2
  FROM table2
) t
ORDER BY rs

答案 2 :(得分:3)

;WITH cte as (
    SELECT name, surname, 1 as n FROM table1
    UNION ALL
    SELECT name, surname, 2 as n FROM table2
    UNION ALL
    SELECT name, surname, 3 as n FROM table3
)
SELECT name, surname
FROM cte
ORDER BY n;

答案 3 :(得分:1)

。喜欢这个?

CREATE TABLE #Table1 (Names VARCHAR(50))
CREATE TABLE #Table2 (Names VARCHAR(50))

INSERT INTO #Table1
(
    Names
)
VALUES
    ('John Doe'), ('Bob Marley'), ('Ras Tafari') 

INSERT INTO #Table2
(
    Names
)
VALUES
    ('Lucky Dube'), ('Abby Arnold') 


SELECT ArbSeq   = 1, *
FROM #Table1
UNION ALL
SELECT ArbSeq   = 2, *
FROM #Table2
ORDER BY ArbSeq

应该注意,未明确定义时不保证排序。 如果表具有聚簇索引,则通常会按索引的顺序返回行 - 但这不能保证。