我有2个表,我想做一个查询并根据它们的外键对它们进行分组。这是一个例子:
部门
DEPART_ID(PK) - DEPART_NAME
1 - Accounting
2 - IT
员工
EMP_ID(PK) - NAME - SURNAME - DEPART_ID(FK)
1 - John - John - 1
2 - George - George - 2
管理者
MANAG_ID(PK) - NAME - SURNAME - DEPART_ID(FK)
1 - Nick - Nick - 1
2 - Michael - Michael - 2
我希望按照部门名称对此输出进行分组。
Accounting | IT
----------------|-------------------
John John | George George
Nick Nick | Michael Michael
我已经尝试但我不能让它发挥作用。这是最好的方法吗?
答案 0 :(得分:1)
您可以使用此功能获得所需内容:
select * from
(select name || ' ' || Surname Accounting from employees where depart_id = 1),
(select name || ' ' || Surname IT from employees where depart_id =2)
union
select * from
(select name || ' ' || Surname Accounting from managers where depart_id = 1),
(select name || ' ' || Surname IT from managers where depart_id =2)
答案 1 :(得分:0)
这是一个解决方案。子查询格式化名称并为部门内的员工生成连接密钥。主查询将WITH输出拆分为基于depart_id
的子查询,这些查询在生成的密钥上连接;完全外部联接允许部门拥有不同数量的人。
with emps as
( select depart_id,
name || ' ' || Surname ename ,
row_number() over (partition by depart_id order by emp_id) rn
from employees)
select acct.ename as accounting
, it.ename as IT
, sal.ename as sales
, hr.ename as hr
from (select * from emps where department_id = 1) acct
full outer join (select * from emps where department_id = 2) it
on acct.rn = it.rn
full outer join (select * from emps where department_id = 3) sal
on acct.rn = sal.rn
full outer join (select * from emps where department_id = 4) hr
on acct.rn = hr.rn
order by acct.rn, it.rn, sal.rn, hr.rn
/