Union 2表具有相同的SQL Server结构

时间:2016-10-30 19:59:52

标签: sql sql-server union

我有两张表结构相同的表:Table1(Timestamp, Value)Table2(Timestamp, Value)。我希望将这些表联合2作为表格,如Table3(Timestamp, Value1, Value2) Value1 is value of Table1Value2 is value of Table2。我怎么能在SQL Server上做到这一点?

4 个答案:

答案 0 :(得分:2)

试试这个

DECLARE @table1 TABLE (TS int, Value int);
DECLARE @table2 TABLE (TS int, Value int);

DECLARE @table3 TABLE(TS int, Value1 int, Value2 int);


INSERT INTO @table1(TS, Value)
SELECT 1, 12
UNION SELECT 3, 34
UNION SELECT 9, 122

INSERT INTO @table2(TS, Value)
SELECT 1, 23
UNION SELECT 2, 99
UNION SELECT 3, 999
UNION SELECT 5, 1222

- 答案: -

INSERT INTO @table3(TS, Value1, Value2)
SELECT ISNULL(t1.TS, t2.TS), t1.Value, T2.Value
FROM @table1 t1
FULL JOIN @table2 t2 ON t2.TS = t1.TS

SELECT * FROM @table3
ORDER BY TS

上面的示例代码。将TS更改为首选名称和数据类型

答案 1 :(得分:0)

加入这两个表:

SELECT
    Table1.Timestamp,
    Table1.Value as Value1
    Table2.Value as Value2
FROM
    Table1
    inner join Table2
        on Table1.Timestamp = Table2.Timestamp

答案 2 :(得分:0)

尝试以下查询:

SELECT
    Table1.Timestamp,
    Table1.Value as Value1
    Table2.Value as Value2
FROM
    Table1
    Left join Table2
        on Table1.Timestamp = Table2.Timestamp

UNION

SELECT
    Table1.Timestamp,
    Table1.Value as Value1
    Table2.Value as Value2
FROM
    Table1
    RIGHT join Table2
        on Table1.Timestamp = Table2.Timestamp  
WHERE       Table1.Timestamp IS NULL

答案 3 :(得分:0)

为什么不简单地使用UNION?

select TS, value as value1, NULL as value2 FROM T1
UNION
select TS, NULL, value as value2 from T2

这应该适用于大多数DBMS。