I have the following tables:
Employees ------------- ClockNo int CostCentre varchar Department int
and
Departments ------------- DepartmentCode int CostCentreCode varchar Parent int
Departments may have other departments, as parents mean that there is an infinite hierarchy. All departments are cost CostCentreCode , so there will always be a CostCentreCode . If parent = 0 this is the top-level department
Employees must have a CostCentre value, but may have a Department of 0, that is, they are not in a department
What I want to try and generate is a query that will give up to four levels of hierarchy. For example:
EmployeesLevels ----------------- ClockNo CostCentre DeptLevel1 DeptLevel2 DeptLevel3 DeptLevel4
I managed to get something to display the structure of the department on it, but I cannot figure out how to associate this with employees without creating duplicate rows of employees:
SELECT d1.Description AS lev1, d2.Description as lev2, d3.Description as lev3, d4.Description as lev4 FROM departments AS d1 LEFT JOIN departments AS d2 ON d2.parent = d1.departmentcode LEFT JOIN departments AS d3 ON d3.parent = d2.departmentcode LEFT JOIN departments AS d4 ON d4.parent = d3.departmentcode WHERE d1.parent=0;
SQL To create a structure and some sample data:
CREATE TABLE Employees( ClockNo integer NOT NULL PRIMARY KEY, CostCentre varchar(20) NOT NULL, Department integer NOT NULL); CREATE TABLE Departments( DepartmentCode integer NOT NULL PRIMARY KEY, CostCentreCode varchar(20) NOT NULL, Parent integer NOT NULL ); CREATE INDEX idx0 ON Employees (ClockNo); CREATE INDEX idx1 ON Employees (CostCentre, ClockNo); CREATE INDEX idx2 ON Employees (CostCentre); CREATE INDEX idx0 ON Departments (DepartmentCode); CREATE INDEX idx1 ON Departments (CostCentreCode, DepartmentCode); INSERT INTO Employees VALUES (1, 'AAA', 0); INSERT INTO Employees VALUES (2, 'AAA', 3); INSERT INTO Employees VALUES (3, 'BBB', 0); INSERT INTO Employees VALUES (4, 'BBB', 4); INSERT INTO Employees VALUES (5, 'CCC', 0); INSERT INTO Employees VALUES (6, 'AAA', 1); INSERT INTO Employees VALUES (7, 'AAA', 5); INSERT INTO Employees VALUES (8, 'AAA', 15); INSERT INTO Departments VALUES (1, 'AAA', 0); INSERT INTO Departments VALUES (2, 'AAA', 1); INSERT INTO Departments VALUES (3, 'AAA', 1); INSERT INTO Departments VALUES (4, 'BBB', 0); INSERT INTO Departments VALUES (5, 'AAA', 3); INSERT INTO Departments VALUES (12, 'AAA', 5); INSERT INTO Departments VALUES (15, 'AAA', 12);
This gives the following structure (employee hours numbers in square brackets):
Root | |---AAA [1] | \---1 [6] | |---2 | \---3 [2] | \---5 [7] | \---12 | \---15 [8] | |---BBB [3] | \---4 [4] | \---CCC [5]
The request should return the following:
ClockNo CostCentre Level1 Level2 Level3 Level4 1 AAA 2 AAA 1 3 3 BBB 4 BBB 4 5 CCC 6 AAA 1 7 AAA 1 3 5 8 AAA 1 3 5 12 *
* In the case of Employee 8, they are at level 5. Ideally, I would like to show all levels up to level 4, but I'm happy to just show CostCentre in this case