查找事件对-Postgresql
我需要找到员工和他们工作的部门之间可能存在的耦合。我只需要包括两个不同部门的耦合,因此如果一名员工为两个以上的部门工作,我需要将其划分为两个部门的耦合以显示转移。此外,第一部门员工的合同期限必须早于第二部门的合同期限。我需要将这些值列为“first_name”、“last_name”、“deptn1”、“dept1”、“deptn2”、“dept2” 例如,John Doe于2016年1月1日至2016年6月6日为A部门(第9部门)工作,于2016年6月10日至2017年12月12日为B部门(第3部门)工作,结果如下: 约翰,多伊,9,A,3,B 如果他随后回到A部门的工作岗位,应该有另一个这样的耦合,以使他的第二次调动可见: 约翰,多伊,3,B,9,A 因此,如果他四处转移,我们应该有尽可能多的部门耦合,在这种情况下,2个转移,因此3个部门中有2个耦合(A=>B=>A so A,B/B,A) 我有四张桌子查找事件对-Postgresql,sql,postgresql,join,Sql,Postgresql,Join,我需要找到员工和他们工作的部门之间可能存在的耦合。我只需要包括两个不同部门的耦合,因此如果一名员工为两个以上的部门工作,我需要将其划分为两个部门的耦合以显示转移。此外,第一部门员工的合同期限必须早于第二部门的合同期限。我需要将这些值列为“first_name”、“last_name”、“deptn1”、“dept1”、“deptn2”、“dept2” 例如,John Doe于2016年1月1日至2016年6月6日为A部门(第9部门)工作,于2016年6月10日至2017年12月12日为B部门(第
Person (PK email, first_name, last_name, FK postcode, FK place_name)
Employee(PK employeenr, FK email)
Department(PK departmentnr, name, FK postcode, FK place_name)
Contract(PK periode_begin, PK periode_end, FK departmentnr, FK employeenr)
我已经试过了,但我不知道如何使用别名从department.name中获取值,并将它们作为name1和name2放在其他列中。此外,我也找不到一种方法来实现耦合,比如四次传输(a=>B=>C=>D=>E到a,B/B,C/C,D,E)
使用
另请阅读有关窗口函数的内容
SELECT
first_name,
last_name,
d1.departmentnr AS deptnr1,
d1.name AS dept1,
d2.departmentnr AS deptnr2,
d2.name AS dept2,
FROM person
INNER JOIN employee ON employee.email=person.email
INNER JOIN contract ON contract.employeenr = employee.employeenr
INNER JOIN department d1 ON department.departmentnr = contract.departmentnr
where contract.employeenr in
(SELECT employeenr FROM contract
GROUP BY employeenr HAVING COUNT(employeenr)>1
AND COUNT(employeenr)>1)
select
first_name,
last_name,
deptnr1,
dept1,
deptnr2,
dept2
from (
select
first_name,
last_name,
departmentnr as deptnr1,
name as dept1,
lead(departmentnr) over w as deptnr2,
lead(name) over w as dept2,
periode_begin
from person p
join employee e using(email)
join contract c using(employeenr)
join department d using(departmentnr)
window w as (partition by email order by periode_begin)
) s
where deptnr2 is not null
order by first_name, last_name, periode_begin