如何为以下查询添加两个输出或查询并获得一个合并的结果

时间:2018-07-10 14:48:10

标签: oracle

1。

select M.MASTER_REF, case B.Type when 450 Then 'RED'                               
when 420 Then 'RVL'                                                 
END Note_Type, B.CODE, B.NOTE_TEXT, (E.REFNO_PFIX || ''|| E.REFNO_SERL)AS Event_Ref, B.CREATED_AT, B.ACTIVE
from Note B, MASTER M, BASEEVENT E, TIDataItem N
where B.KEY97=N.KEY97 and N.MASTER_KEY=M.KEY97 and E.KEY97 = B.NOTE_EVENT
and M.EXEMPLAR in ('8806648499869051681','8806648499869023154','8806648499869054292','8806648499869006425')
and M.STATUS in ('LIV','EXP')
and B.Code not in ('Migration')
order by M.Master_Ref Asc, B.CREATED_AT desc

2。

select M.MASTER_REF, case B.Type when 450 Then 'RED'
when 420 Then 'RVL'            
END Note_Type, B.CODE, B.NOTE_TEXT, B.Note_Event AS Event_Ref, B.CREATED_AT, B.ACTIVE
from Note B, MASTER M, TIDataItem N
where B.KEY97=N.KEY97 and N.MASTER_KEY=M.KEY97 and B.NOTE_EVENT is null
and M.EXEMPLAR in ('8806648499869051681','8806648499869023154','8806648499869054292','8806648499869006425')
and M.STATUS in ('LIV','EXP')
and B.Code not in ('Migration')
order by M.Master_Ref Asc, B.CREATED_AT desc

1 个答案:

答案 0 :(得分:3)

使用UNION ALL将相似的结果集加在一起。每个集合之间的列顺序和数据类型必须匹配。 ORDER BY仅应位于最后的SELECT处,并且只能引用列别名。

select 
    M.MASTER_REF, 
    case B.Type 
        when 450 Then 'RED' 
        when 420 Then 'RVL' END Note_Type, 
    B.CODE, 
    B.NOTE_TEXT, 
    (E.REFNO_PFIX || ''|| E.REFNO_SERL) AS Event_Ref, 
    B.CREATED_AT, 
    B.ACTIVE
from 
    Note B, 
    MASTER M, 
    BASEEVENT E, 
    TIDataItem N
where 
    B.KEY97=N.KEY97 and 
    N.MASTER_KEY=M.KEY97 and 
    E.KEY97 = B.NOTE_EVENT and 
    M.EXEMPLAR in ('8806648499869051681','8806648499869023154','8806648499869054292','8806648499869006425') and 
    M.STATUS in ('LIV','EXP') and 
    B.Code not in ('Migration')

UNION ALL

select 
    M.MASTER_REF, 
    case B.Type 
        when 450 Then 'RED'
        when 420 Then 'RVL' END Note_Type, 
    B.CODE, 
    B.NOTE_TEXT, 
    TO_CHAR(B.Note_Event) AS Event_Ref, 
    B.CREATED_AT, 
    B.ACTIVE
from 
    Note B, 
    MASTER M, 
    TIDataItem N
where 
    B.KEY97=N.KEY97 and 
    N.MASTER_KEY=M.KEY97 and 
    B.NOTE_EVENT is null and 
    M.EXEMPLAR in ('8806648499869051681','8806648499869023154','8806648499869054292','8806648499869006425') and 
    M.STATUS in ('LIV','EXP') and 
    B.Code not in ('Migration')
order by 
    Master_Ref Asc, 
    CREATED_AT desc

我强烈建议您避免使用旧的联接语法,因为它会使代码的可读性降低(使用带有适当INNER子句的显式LEFT JOINON):

更改:

from 
    Note B, 
    MASTER M, 
    TIDataItem N
where 
    B.KEY97=N.KEY97 and 
    N.MASTER_KEY=M.KEY97

针对:

FROM
    Note B
    INNER JOIN TIDataItem N ON B.KEY97 = N.KEY97
    INNER JOIN MASTER M ON N.MASTER_KEY = M.KEY97