外连接与union

 

一道有点意思的oracle试题现转如下:

有两个表,表a有两个字段,分别是部门code和子部门code,表b有两个字段,部门code,和部门name

表sectionCfg 如下:                              表sectionINfo: 

secID     subSecID                         secID          secName 
2                   5                                       2                   部门2  
2                   6                                       3                   部门3
3                   7                                       4                   部门4
3                   8                                       5                   科1
4                   9                                       6                   科2
4                   10                                     7                   科1
                                                            8                   科2
                                                            9                   科1  
                                                            10                 科2

想输出这样的结果:  
secID  secName  subName
2           部门2
5           部门2          科1  
6           部门2          科2  
3           部门3  
7           部门3          科1  
8           部门3           科2  
4           部门4  
9           部门4           科1  
10        部门4           科2 
 
我自己的解决思路:
运用外连接最后实现三列的结果集
表A:secID   部门Name 即结果集的第一列和第二列
表B:secid   subname 即科室的id和name
然后表A表B外连接得到最终结果
难点在于得到表A
把部门和子部门分开考虑利用union合并。两次引用sectionInfo表
select  A.secid,
       A.secname,
       B.SECNAME
from  
        (
select distinct  i.SECID,
             i.SECNAME
        
from
 sectioncfg c,
                sectioninfo i
        
where c.SECID =
 i.SECID
    
union
 
        
select
 c.SUBSECID,
       i2.SECNAME
       
from
 sectioncfg c,
     sectioninfo i,
     sectioninfo i2
       
where i.SECID = c.SUBSECID and

      c.SECID 
=  i2.SECID
    
order by
 secname )  A,
        (
select  i.SECID,
    i.SECNAME
          
from  sectioncfg c,
     sectioninfo i
          
where  i.SECID  =  c.SUBSECID
          
order   by  i.SECID)  B
where  A.secid  =  B.secid( + )  
order   by  A.secname,A.secid

另一种类似的思路,但简单

 

select  aa.subsecid,
       b2.secname,
       decode(b1.secname,b2.secname,
null ,b1.secname)  as  subdep
  
from  (
        
select  c.SUBSECID,
               c.SECID
          
from  sectioncfg c
        
union   all
        
select   distinct
               c.SECID,
               c.SECID
          
from  sectioncfg c
          
order   by  secid
       )aa,
       sectioninfo b1,
       sectioninfo b2
 
where  aa.secid  =  b2.secid
   
and  aa.subsecid  =  b1.secid
 
order   by   2 , 1 ;

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值