SQL: 如何从具有一对多关系的表创建数据库视图?

SQL: How to create a database view from tables with OneToMany Relationship?

有三个可用的 table 和列:

Core - EmpID, EmpName
       1, Yagga Boshu

External - ExternalEmpID, ExternalDeptName
           1 , Capegemini

Position - EmpID, Dept  P/S
           1, IT        Primary
           1, Finance   Secondary

我想按以下格式创建视图:

   Emp ID, EmpName, ExternalID, ExternalName, EmpPrimaryDept, EmpSecondaryDept
   1,     Yagga Boshu,  1 ,      CapeGemini  ,  IT,           FINANCE
  1. EmpID 和 EmpName 来自 Core Table。
  2. ExternalID 和 ExternalName 来自 External Table 是 OneToOne with core table
  3. EmpPrimaryDept 和 EmpSecondaryDept 来自位置 Table 其中 是 OneToMany 与核心 table

对于 1) 和 2) 以下查询有效:

select * from CORE ec, EXTERNAL ee
where ec.EMPLOYEEID = ee.ExternalEmpID

如何加入位置 table 以便 return 如上所述排成一排?

也许你只需要 LISTAGG在加入二级部门的 3 个表后。

    select EmpID, ec.EmpName
   , ee.ExternalDeptName
       ee.Dept, 
         LISTAGG(p.dept,',') as 
        'PrimarySecondaryDepts.' from
        CORE ec join EXTERNAL ee 
       on ec.empid =ee.empid join 
       Position p
        ec.empid=p.empid group by empid, 
         ec.empname, 
       ee.ExternalDeptName,
       ee.Dept

一种方法是在 select 子句中使用子查询:

select
  c.empid, c.empname, e.externaldeptname,
  (select dept from position p where p.empid = c.empid and p.p_s = 'Primary') as dept1,
  (select dept from position p where p.empid = c.empid and p.p_s = 'Secondary') as dept2
from core c
left join external e on e.externalempid = c.empid
order by c.empid;

您也可以将它们移动到 from 子句:

select
  c.empid, c.empname, e.externaldeptname, p.dept as dept1, s.dept as dept2
from core c
left join external e on e.externalempid = c.empid,
left join (select empid, dept from position where p_s = 'Primary') p on p.empid = c.empid
left join (select empid, dept from position where p_s = 'Secondary') s on s.empid = c.empid
order by c.empid;