How to execute UNION without sorting? (SQL)

前端 未结 10 614
猫巷女王i
猫巷女王i 2021-01-30 21:34

UNION joins two results and remove duplicates, while UNION ALL does not remove duplicates.
UNION also sort the final output.

W

10条回答
  •  臣服心动
    2021-01-30 22:10

    select T.Col1, T.Col2, T.Sort
    from 
        (
          select T.Col1,
                 T.Col2,
                 T.Sort,
                 rank() over(partition by T.Col1, T.Col2 order by T.Sort) as rn
          from
              (
                select Col1, Col2, 1 as Sort
                from Table1
                union all
                select Col1, Col2, 2
                from Table2
              ) as T
        ) as T
    where T.rn = 1    
    order by T.Sort
    

提交回复
热议问题