I have the following relation:
CompanyInfo(company, role, employee)
What I'm trying to do is to find the shortest "path" between two employees.
Example
I need to find the distance between Joe and Peter. Joe is the CEO of Company A, and a person named Alex is a board member. Alex is the CEO of Company B, and Peter is a vice president at Company B. Then, the distance between Joe and Peter will be 2. If Joe and Peter had roles in the same company, it would be 1.
I need to solve this using recursive SQL. So far I've come up with the base case and the final select string, but I can't for the life of me figure out the recursive part.
WITH RECURSIVE shortest_path(c1,p1,c2,p2, path) AS (
-- Basecase --
SELECT c1.company, c1.person, c2.company, c2.person, array[c1.person, c2.person]
FROM CompanyInfo c1
INNER JOIN CompanyInfo c2 ON c1.company = c2.company
WHERE c1.person = 'Joe'
AND c1.person <> c2.person
UNION ALL
-- Recursive --
-- This is where I'm stuck.
)
SELECT p1, p2, array_length(path,1) -1 as distance
FROM shortest_path
WHERE p2 = 'Peter'
ORDER BY distance
LIMIT 1;
Sample Data
CREATE TABLE CompanyInfo (
company text,
role text,
employee text,
primary key (company, role, employee)
);
insert into CompanyInfo values('Company A', 'CEO', 'Joe');
insert into CompanyInfo values('Company A', 'Board member', 'Alex');
insert into CompanyInfo values('Company B', 'CEO', 'Alex');
insert into CompanyInfo values('Company B', 'Board member', 'Peter');
Expected Output
person 1 | person 2 | distance
Joe Peter 2