如何使用选择性重复记录连接表? (oracle10g的)

时间:2016-06-29 05:13:03

标签: sql oracle oracle10g

如何针对以下要求创建 ORACLE 查询?

问题是如果某些SQL结果中存在相同的ID,如何获取该ID的记录,其中Name不为空或NULL。

Pattern(1)
SQL1 => RESULT1 =>    ID     NAME
                     -----  ------
                      001
                      002
                      003

SQL2 => RESULT2 => ID NAME ----- ------ 003 NAME1

SQL3 => RESULT3 => ID NAME ----- ------ 003 NAME2

Pattern(2)
SQL1 => RESULT1 =>    ID     NAME
                     -----  ------
                      001
                      002
                      003    NAME1

SQL2 => RESULT2 => ID NAME ----- ------ 003

SQL3 => RESULT3 => ID NAME ----- ------ 003 NAME2

Pattern(3)
SQL1 => RESULT1 =>    ID     NAME
                     -----  ------
                      001
                      002
                      003   

SQL2 => RESULT2 => ID NAME ----- ------ 003 NAME1 003 NAME2

SQL3 => RESULT3 => ID NAME ----- ------

如何将这3个结果加入以下结果?

                      ID     NAME
                     -----  ------
                      001
                      002
                      003    NAME1
                      003    NAME2

2 个答案:

答案 0 :(得分:2)

一个选项是将UNIONSQL2表格SQL3放在一起,然后将此结果重新加入SQL1

SELECT t1.ID, t1.NAME
FROM SQL1 t1 LEFT JOIN
(
    SELECT ID, NAME
    FROM SQL2
    UNION ALL
    SELECT ID, NAME
    FROM SQL3
) t2
    ON t1.ID = t2.ID

答案 1 :(得分:1)

这适用于您的场景

with tbl(id,name) as
(query1 
 union all
query2
 union all
query 3
)
select * From tbl where name is null
 and id not in
    (select id from tbl where name is not null)
union all
select * from tbl where name is not null

我创建了示例

with tbl(id,name) as
(select 1,null from dual union all
select 2,null from dual union all
select 3,null from dual union all
select 3,'NAME1' from dual union all
select 3,'NAME2' from dual)

select * From tbl where name is null
 and id not in
    (select id from tbl where name is not null)
union all
select * from tbl where name is not null

输出

id  name
---------
1   
2   
3   NAME1
3   NAME2