Sql server union but keep order

前端 未结 4 695
悲&欢浪女
悲&欢浪女 2020-12-05 09:58

Is there a way to union two tables, but keep the rows from the first table appearing first in the result set?

For example:

Table1

name                


        
相关标签:
4条回答
  • 2020-12-05 10:23
    ;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;
    
    0 讨论(0)
  • 2020-12-05 10:33

    The only way to guarantee output order is to use ORDER BY:

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

    If you don't want rs to appear in the final result set, do the UNION as a subquery:

    SELECT name,surname
    FROM (
      SELECT name,surname,1 as rs
      FROM table1
      UNION ALL
      SELECT name,surname,2
      FROM table2
    ) t
    ORDER BY rs
    
    0 讨论(0)
  • 2020-12-05 10:35

    Try this :-

    Select * 
    from
    ( 
    Select name,surname, 1 as filter
    from  Table1
    Union all
    Select name,surname , 2 as filter
    from Table2
    )
    order by filter
    
    0 讨论(0)
  • 2020-12-05 10:36

    .Like this?

    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
    

    It should be noted that ordering is not guaranteed when not explicitly defined. If the table features a clustered index, the rows will typically be returned in the index's order - but this is not guaranteed.

    0 讨论(0)
提交回复
热议问题