如何加入 table 与选择性重复记录? (oracle10g)
How to join table with selective duplicate records? (oracle10g)
如何为以下要求创建 ORACLE 查询?
问题是,如果SQL个结果中存在相同的ID,如何获取Name不为空或NULL的那个ID的记录。
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
一个选择是 UNION
将 SQL2
和 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
这适用于您的场景
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
如何为以下要求创建 ORACLE 查询?
问题是,如果SQL个结果中存在相同的ID,如何获取Name不为空或NULL的那个ID的记录。
Pattern(1) SQL1 => RESULT1 => ID NAME ----- ------ 001 002 003SQL2 => RESULT2 => ID NAME ----- ------ 003 NAME1
SQL3 => RESULT3 => ID NAME ----- ------ 003 NAME2
Pattern(2) SQL1 => RESULT1 => ID NAME ----- ------ 001 002 003 NAME1SQL2 => RESULT2 => ID NAME ----- ------ 003
SQL3 => RESULT3 => ID NAME ----- ------ 003 NAME2
Pattern(3) SQL1 => RESULT1 => ID NAME ----- ------ 001 002 003我怎样才能把这3个结果合并成下面的结果?SQL2 => RESULT2 => ID NAME ----- ------ 003 NAME1 003 NAME2
SQL3 => RESULT3 => ID NAME ----- ------
ID NAME ----- ------ 001 002 003 NAME1 003 NAME2
一个选择是 UNION
将 SQL2
和 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
这适用于您的场景
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