如何组合这两个表并创建一个新表?

时间:2017-06-03 09:43:03

标签: sql sql-server

如何组合两个表并创建一个新表

第一张表:

NavContainer

第二张表

ExitDate      |   fullname     | outputnumber    
------------------------------------------------
2012/01/01         a              10    
2012/01/06         b              2    
2012/01/08         c              3    
2012/01/12         d              4

答案表

inputnumber   |   date
-------------------------------
  100              2012/01/05
  150              2012/01/07
  200              2012/01/10

注意:日期和位置很重要,我使用的是sql server

3 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要union all。像这样:

select * from (
    select ExitDate, fullname, outputnumber, NUll as inputnumber, NUll as [date] from first_table
    union all
    select NUll as ExitDate, NUll as fullname, NUll as outputnumber, inputnumber, [date] from second_table
) t
order by coalesce(ExitDate, [date])  

然后,整个结果按ExitDatedate

的组合日期排序

rextester demo

答案 1 :(得分:1)

我认为你可以有一个更好的表格:

select *
from (
    select fullname, 0 as io, outputnumber as number, ExitDate as date
    from table1
    union all
    select '-', 1, inputnumber, date) t
order by date, io;

fullname | io | number | date
---------+----+--------+-------------
a        | 0  | 10     | 2012/01/01
-        | 1  | 100    | 2012/01/05
b        | 0  | 2      | 2012/01/06
-        | 1  | 150    | 2012/01/07
c        | 0  | 3      | 2012/01/08
-        | 1  | 200    | 2012/01/10
d        | 0  | 4      | 2012/01/12

答案 2 :(得分:1)

您可以使用full outer join获得所需的确切输出:

select t1.*, t2.*
from t1 full outer join
     t2
     on 1 = 0
order by coalesce(t1.exitdate, t2.date);