This is my database:
- Employee (id, department_id, name)
- Department(id, name)
- Project(id, departament_id)
- Work (employee_id, project_id)
With PK, FK (for example: Employee has PK id and FK departament_id (id) from Department)
I want to select all the employees (E.name) that are working in all projects of a certain department (Development, for example).
This is my query:
SELECT E.name,
COUNT(P.id) AS PW,
AVG(DISTINCT(Q.allproj)) AS PrjOfDep
FROM Employee E
JOIN WORK W
ON W.employee_id= E.id
JOIN Project P
ON P.id = W.project_id
JOIN (SELECT D.id,
COUNT(P1.id) AS allproj
FROM Project P1
JOIN Department D
ON P1.departament_id = D.id
AND D.name = "Development"
GROUP BY D.id) Q ON P.departament_id = Q.id
GROUP BY E.ID HAVING PW = PrjOfDep
This is kinda working, this is the result:
Name PW PrjOfDep
Stark 2 2.0000
Mike 2 2.0000
I didn't know how to check if all the projects where Employee E is working include all the projects of departament "development", so I did a trick and my query looks very ugly. I counted all the projects where Employee E is working in Development and I compared that with the number of project of Departament "Development".
PrjOfDep is an average, I did this ugly trick because the query
SELECT E.name,
COUNT(P.id) AS PW
FROM Employee E
JOIN WORK W
ON W.employee_id = E.id
JOIN Project P
ON P.id= W.project_id
JOIN (SELECT D.id,
COUNT(P1.id) AS allproj
FROM Project P1
JOIN Department D
ON P1.departament_id= D.id
AND D.name = "Development"
GROUP BY D.id) Q
ON P.departament_id= Q.id
GROUP BY E.id HAVING PW = Q.allproj
gives me the error:
1054 - Unknown column 'Q.allproj' in 'having clause'
I want a more elegant query for my problem and I want to see only the name of the Employee. Thanks!