2014-05-04 24 views
0

我需要为报告获取数据。我有2个表A和B. 表A有许多用于相同ID的插入,并且可以只有表中的条目或与表B共享数据, 表B可以只有表中的条目或与表A共享数据。Oracle仅从表A获取数据,仅从表B获取并共享

Create table A (
    id number, 
    name varchar2(30), 
    seq number 
); 

Create table B (
    name_s varchar2 (30), 
    a_id number 
); 

insert into A (id, name,seq) values (1, 'first',1); 
insert into A (id, name,seq) values (3, 'first',2); 
insert into A (id, name,seq) values (1, 'second',3); 
insert into A (id, name,seq) values (2, 'first',4); 
insert into A (id, name,seq) values (2, 'second',5); 
insert into A (id, name,seq) values (1, 'third',6); 
insert into A (id, name,seq) values (3, 'second',7); 
insert into A (id, name,seq) values (1, 'fourth',8); 
insert into A (id, name,seq) values (1, 'fifth',9); 
insert into A (id, name,seq) values (1, 'sixth',10); 
insert into A (id, name,seq) values (2, 'third',11); 
insert into A (id, name,seq) values (3, 'third',12); 

insert into B (name_s, a_id) values ('sale1', 3); 
insert into B (name_s, a_id) values ('sale2', null); 
insert into B (name_s, a_id) values ('sale3', 1); 

现在我想返回的数据: 一切从表A,但不是在B,一切从表B,而不是在A和一切他们分享什么,但如果B连接与A - 它应该从B表中返回最近的条目与来自B表的a_id。

所以我希望退货:

column headers: A_id, A_name, A_seq, B_name 
    --everything what is not in table B 
     (2, 'first',4, null); 
     (2, 'second',5, null); 
     (2, 'third',11, null); 
    --everything what is not in table A 
    (null, null,null, 'sale2'); 
    --everything what is shared 
    (3, 'third', 12,'sale1'); 
    (1, 'sixth', 10,'sale3'); 

我的解决方案是运行3个查询来获得这些数据:

--just from table A 
select * from A where id not in (select nvl(a_id,-1) from B); 
--just from table B 
select * from B where a_id is null; 
--shared 
select * from B,A where B.a_id = A.id and A.seq = 
(select max(seq) from A where A.id = B.a_id); 

有没有更好的办法是使用连接做(我试过但它总是让我比预期的更多)?只运行一个或两个而不是3个查询?

这里是链接到小提琴例如:http://sqlfiddle.com/#!4/9fdb3/3

感谢

回答

3

如果我理解正确的逻辑,你可以做你想做一个full outer join和一些额外的逻辑是什么:

select coalesce(a.id, b.a_id) as id, 
     a.name, 
     a.seq, 
     b.name_s, 
     (case when a.id is not null and b.name_s is not null 
      then 'Both' 
      when a.id is not null 
      then 'A-Only' 
      else 'B-Only' 
     end) as which 
from (select a.*, 
      row_number() over (partition by id order by seq desc) as seqnum 
     from a 
    ) a full outer join 
    b 
    on a.id = b.a_id 
where b.name_s is not null and coalesce(a.seqnum, 1) = 1 or b.name_s is null; 

的Twist正在处理where子句中的奇怪排序逻辑 - 只有最近的A存在匹配时才有效,而当没有匹配时只需要最新的A。这会在SQL小提琴中产生你想要的结果。