加入2个类似的SQL Server表

时间:2011-03-01 06:08:21

标签: sql sql-server tsql sql-server-2008

我有两张桌子:

table1
    id someval 
    -----------
    1      23  
    2      56  
    3      76  
    4     456  
    5      53  
    6      67  
    7      12  
    8      43  
    9      99  
    10    567
    11     55
    12      6
    13     55
    14     56
    15      1
    16    444
    17     66 
    18     89
    19      6    


table2
    id someval 
    -----------
    1     23.3 
    2     5.6  
    3     8.76 
    4     4.56 
    5      5.3 
    6      6.7 
    7      1.2 
    8      4.3 
    9      9.9 
    10    56.7
    11     6.7
    12    44.8 

什么查询将连接它们并输出(id被修改为第二个表):

table1AND2

    id someval 
    -----------
    1      23  
    2      56  
    3      76  
    4     456  
    5      53  
    6      67  
    7      12  
    8      43  
    9      99  
    10    567
    11     55
    12      6
    13     55
    14     56
    15      1
    16    444
    17     66 
    18     89
    19      6   
    20    23.3 
    21    5.6  
    22    8.76 
    23    4.56 
    24    5.3 
    25    6.7 
    26    1.2 
    27    4.3 
    28    9.9 
    29    56.7
    30    6.7
    31    44.8 

对于任何行大小的任何2个表,是否有办法执行此操作?

3 个答案:

答案 0 :(得分:4)

使用:

  SELECT a.id,
         a.someval
    FROM TABLE1 a
UNION ALL
  SELECT b.id + (SELECT MAX(id) FROM TABLE1) AS id,
         b.someval
    FROM TABLE2 b
ORDER BY id

UNION删除重复项; UNION ALL不会删除重复项,并且速度更快。

要插入另一张表:

INSERT INTO another_table
  SELECT a.id,
         a.someval
    FROM TABLE1 a
UNION ALL
  SELECT b.id + (SELECT MAX(id) FROM TABLE1) AS id,
         b.someval
    FROM TABLE2 b
ORDER BY id

...假设只有两列,id& somecol / etc,在新表中。

答案 1 :(得分:0)

我认为这会奏效。目前无法测试......

SELECT identity(int,1,1) as id, 
   (
       SELECT someval FROM table1 
       UNION 
       SELECT someval FROM table2
   ) 

答案 2 :(得分:0)

您可以使用Union All谓词生成所询问的输出,并从第一个表中提取最高值。

Select id, somevalue From Table1
Union All
Select id
    + (Select Max(id) From Table1)
    , somevalue 
From Table2

另一种解决方案是使用CTE:

With UnionedData As
    (
    Select id, somevalue, 1 As Sort From Table1
    Union All
    Select id, somevalue, 2 From Table2
    )
Select Row_Number() Over( Order By Sort, Id ) As Id
    , somevalue
From UnionedData