将两个以上的表合并为一个

时间:2018-04-19 14:13:07

标签: sql oracle

我有2平方英尺,它们具有相同的结构但返回不同的数据。我想合并这两个表,例如它从两个表中获取数据。我尝试了联合但它没有提供所需的输出。

SQL1:

    select 
    distinct Job,
    case job_status 
        when 'B' then 'GREEN'
        when 'E' then 'RED'
    end as 'M_Job_Status'
 from 
    job_scheduler 
where 
    convert (varchar,job_run_date,101) = '{0}' 
    and job_type in ('Morning_Jobs')

返回:

Job         |M_Job_Status|
------------------------
job1        | green     |
job2        | green     |

sql2:

 select 
    distinct Job,
    case job_status 
        when 'B' then 'GREEN'
        when 'E' then 'RED'
    end as 'E_Job_Status'
 from 
    job_scheduler 
where 
    convert (varchar,job_run_date,101) = '{0}' 
    and job_type in ('Evening_Jobs')

返回:

Job         |E_Job_Status|
------------------------
job1        | green     |
job2        | green     |

我希望结果是:

 Job        |M_Job_Status|E_Job_Status|
----------------------------------------
job1        | green      | green
job2        | green      | green 

我尝试了Union,但是显示了状态列,一个在另一个之下,我希望它是并排的。

1 个答案:

答案 0 :(得分:1)

尝试在CTE中包装两个查询中的每一个并将它们连接在一起:

WITH cte1 AS ( sql1 ),
cte2 AS ( sql2 )

SELECT
    t1.Job,
    t1.M_Job_Status,
    t2.E_Job_Status
FROM cte1 t1
LEFT JOIN cte2 t2
    ON t1.Job = t2.Job