我有2个表:警报和闭路电视。
警报表包括:警报ID和日期。
CCTVs表还包括:cctv_ID和日期。
我想将两个表组合在一起,以使其产生一个包含三列的表:cctv_ID,alarm_ID和日期。如果cctv_ID的值具有alarm_ID,则它将为null;如果alarm_ID的值具有cctv_ID,则将为null。
如何将这两个表合并在一起?
警报表:
alarm_ID | Date
1 | 1/1/10
cctv表:
cctv_ID | Date
1 | 2/1/10
最终表应如下所示:
alarm_ID | CCTV_ID | Date
1 | null | 1/1/10
null | 1 | 2/1/10
我目前有以下代码:
with alarms as(
select alarm_id, last_maintenance_date
from REMOTE_SECURITY.alarms
where last_maintenance_date < '4/4/18'),
cctvs as (
select cctv_id, last_maintenance_date
from REMOTE_SECURITY.cctvs
where last_maintenance_date <'4/4/18')
select * from alarms
union
select * from cctvs
;
但是此代码只给我alarm_id列和date列,并且将cctv_id合并到同一列中,所以我不知道哪个是警报,哪个是cctv!
任何帮助将不胜感激!
答案 0 :(得分:1)
使用UNION
select alarm_id,'' AS cctv_id, last_maintenance_date
from REMOTE_SECURITY.alarms
where last_maintenance_date <'4/4/18')
UNION
select '' AS alarm_id,cctv_id, last_maintenance_date
from REMOTE_SECURITY.cctvs
where last_maintenance_date <'4/4/18')
答案 1 :(得分:1)
您可以通过贡献case..when
语句来使用这样的逻辑:
select (case when col0 = 'a' then 1 end) as alarm_ID,
(case when col0 = 'c' then 1 end) as CCTV_ID,
q.last_maintenance_date as Date
from
(with alarms(alarm_ID,last_maintenance_date) as
(select 1, date'2010-01-01'),
cctvs(cctv_ID,last_maintenance_date) as
(select 1, date'2010-01-02')
select 'a' as col0,a.* from alarms a
union all
select 'c' as col0,c.* from cctvs c
) q;