更具体地说,我应该使用递归psql解决问题。我们有这个:
使用递归SQL,查找包含3、4或5名员工的所有周期,其中每个员工在一家公司中担任CEO角色,而在下一周期中担任董事,副董事长或董事长。
-- This is the table in mind:
CREATE TABLE info (
company text
job text
employee text
primary key (company, job, employee)
);
-- Desired result
Cycle Employee Job Company
-------------------------------------------
1 Jonathan CEO DillCO
1 Joseph CEO Joestar
2 Jonathan Chairman Joestar
2 Joseph Director DillCO
我不是特别擅长SQL,但是我正在学习。您可以按照自己的方式解释此问题,而不必完全像我想要的输出(因为这是我对它的解释)。
以下是一些您可以插入表格中的示例数据:
insert into info values('Bolk', 'CEO', 'Stein Hald');
insert into info values('Forsk', 'Chairman', 'Stein Hald')
insert into info values('Bolk', 'Chairman', 'Guro Dale');
insert into info values('Bolk', 'Director', 'Rolf Numme');
insert into info values('Bonn', 'CEO', 'Hauk Storm');
insert into info values('Bonn', 'Chairman', 'Live Brog');
insert into info values('Bonn', 'Director', 'Tor Fjeld');
insert into info values('Braga', 'CEO', 'Truls Lyche');
insert into info values('Hiro', 'Deputy chairman', 'Rolf Numme');
insert into info values('Hafn', 'Chairman', 'Hauk Storm');
这是我所拥有的:
-- so far, finds all CEOs recursively in the first cycle
WITH RECURSIVE cycle (emp, job, comp, cyclenr) AS (
SELECT si.employee, si.job, si.company, 1
FROM info si
UNION ALL
SELECT c.emp, c.job, c.comp, c.cyclenr+1
FROM cycle c
JOIN info c2 on c.emp = c2.employee
WHERE cyclenr < 1
)
SELECT * FROM cycle
WHERE job = 'CEO';
这只会在第一个周期中找到所有CEO,但其余的我都遇到了麻烦。
答案 0 :(得分:0)
这是个主意。筛选出仅首席执行官。然后生成它们的所有组合并检查周期。
对于3的周期,它看起来像:
with ec as (
select distinct employee, company
from info
where job = 'CEO'
)
select *
from ec ec1 join
ec ec2
on ec1.employee <> ec2.employee join
ec ec3
on ec3.employee not in (ec1.employee, ec2.employee)
where exists (select 1
from info i
where i.employee = ec2.employee and i.company = ec1.company and i.job in ('Chairman', 'Director')
) and
exists (select 1
from info i
where i.employee = ec3.employee and i.company = ec2.company and i.job in ('Chairman', 'Director')
) and
exists (select 1
from info i
where i.employee = ec1.employee and i.company = ec3.company and i.job in ('Chairman', 'Director')
) ;
Here是一个示例。