[英]How to combine two different tables with different columns
I have a situation where I need to combine two different tables with different columns. 我遇到一种情况,需要将两个不同的表与不同的列组合在一起。
DDL : 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');
I have different columns in two different tables. 我在两个不同的表中有不同的列。 And I need to combine it as shown in screenshot using SQL.
而且我需要使用SQL将其合并,如屏幕截图所示。
Use union all 全部使用工会
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
You can use INNER JOIN
for this 您可以为此使用
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;
使用以下代码
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.