如何从不同的表创建两个超集

时间:2013-05-07 00:53:06

标签: sql oracle

这些是我的表格。

Main
------
mainid(PK)     
1           
2                    
3           


Emp
-----
empid(PK)    Name      
1            Dave            
2            Dan            
3            Mark            
4            Steve     
5            Elvis
6            Jacob

Tools
-----
toolid(PK)         
1                       
2                        
3                        
4                 
5            
6            


MainEmp
-----
mainid(FK)   empid(FK)      
1            1            
1            2            
2            3            
2            4            
3            5
3            6

MainTools
-----
mainid(FK)   tools(FK)      
1            1            
1            2            
1            3            
2            4            
3            5
3            6

我想实现此查询结果

mainid       emp            tools     
1            Dave, Dan       1,2,3     
2            Mark, Steve     4            
3            Elvis,Jacob     5,6

我正在使用以下sql

 select m.mainid,
 listagg(emp.name, ',') within group (order by emp.empid)
 from main m join
 mainemp me
 on m.mainid = me.mainid join
 emp e
 on e.empid = me.empid
 group by m.mainid

如果我尝试使用工具显示带有emp或main的main,它确实有用。但是我无法弄明白如何将它们连接在一起。请帮忙

2 个答案:

答案 0 :(得分:1)

您需要在子查询中进行聚合,然后将它们连接在一起:

select m.*, n.names, mt.tools
from main m left outer join
     (select me.mainid, listagg(e.name, ',') within group (order by e.name) as names
      from MainEmp me join
           Employees e
           on e.empid = me.empid
      group by me.mainid
     ) n
     on m.mainid = n.mainid
     (select mt.mainid, listagg(mt.tools, ',') within group (order by mt.tools) as tools
      from MainTools mt
      group by mt.mainid
     ) mt
     on m.mainid = mt.mainid

答案 1 :(得分:1)

如果是oracle 11g,你也可以这样做:

SELECT DISTINCT A.MAINID,
WM_CONCAT(DISTINCT C.NAME) OVER(PARTITION BY A.MAINID) AS NAMES,
WM_CONCAT(DISTINCT D.TOOLS) OVER(PARTITION BY A.MAINID ) AS TOOLS
FROM 
MAIN A JOIN MAINEMP B
ON A.MAINID=B.MAINID
JOIN EMP C
ON B.EMPID=C.EMPID
JOIN MAINTOOLS D
ON A.MAINID=D.MAINID