user1736700
user1736700

Reputation: 43

Union 2 tables have same structure SQL Server

I have 2 tables with same structure ex: Table1(Timestamp, Value) and Table2(Timestamp, Value). I want union 2 these tables as a table like: Table3(Timestamp, Value1, Value2) where Value1 is value of Table1 and Value2 is value of Table2. How can I do that on SQL Server?

Upvotes: 2

Views: 492

Answers (4)

dmg
dmg

Reputation: 4481

Why don't you simply use UNION?

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

This should work in most DBMSs.

Upvotes: 0

Hadi
Hadi

Reputation: 37313

Try the following query:

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

Upvotes: 0

Frode
Frode

Reputation: 3455

Try this

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

-- ANSWER: --

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

Example code above. Change TS to preferred name and data type

Upvotes: 2

McNets
McNets

Reputation: 10807

Join this two tables:

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

Upvotes: 0

Related Questions