如何将两个不同的表与不同的列组合

时间:2018-09-27 06:44:13

标签: sql

我遇到一种情况,需要将两个不同的表与不同的列组合在一起。

As shown in this screenshot

DDL

create table tableA ([timestamp] datetime, [source] char(1), [description] varchar(20));
insert into tableA values
('2018-10-12', 'a', 'first day'),
('2018-10-13', 'b', 'alarms'),
('2018-10-14', 'c', 'processing');

create table tableB ([timestamp] datetime, entity varchar(20));
insert into tableB values
('2018-10-12', 'new env'),
('2018-10-13', 'resource'),
('2018-10-18', 'integrated');

我在两个不同的表中有不同的列。而且我需要使用SQL将其组合起来,如屏幕截图所示。

4 个答案:

答案 0 :(得分:2)

全部使用联盟

select a.timestamp, a.source,a.description,b.entity
from tableA a left join tableB b on a.timestamp=b.timestamp 
where b.timestamp is not null
union all
select b.timestamp, a.source,a.description,b.entity
from tableA a right join tableB b on a.timestamp=b.timestamp 
where a.timestamp is null

答案 1 :(得分:1)

您可以为此使用INNER JOIN

SELECT a.TimeStamp, a.Source, a.Description, b.Entity 
FROM TableA a
LEFT JOIN Tableb b ON a.TimeStamp=b.TimeStamp; 
UNION
SELECT a.TimeStamp, a.Source, a.Description, b.Entity 
FROM TableA a
RIGHT JOIN Tableb b ON a.TimeStamp=b.TimeStamp; 

答案 2 :(得分:0)

您需要使用full join。尝试以下查询:

select coalesce (a.timestamp, b.timestamp), source, description, entity
from tableA a
full join tableB b on a.timestamp = b.timestamp

Demo

答案 3 :(得分:0)

使用以下代码

SELECT isnull(t1.TimeStamp, t2.TimeStamp) TimeStamp, t1.source,t1.description, t2.entity from table1 t1 FULL OUTER JOIN table2 t2 on t1.id=t2.id
相关问题