Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the names of projects where all employees currently working on that project work in the same department?

I am new to sql, and am trying to firgure our how to "find the names of projects where all employees currently working on the project work in the same department." For this problem, we have three tables. This problem could be simplified if this data was stored in fewer tables. But lets assume we can’t modifity our tables, and have to make a queery.

"employeeproject"
Our project table that we can refer to with our empid

empid projectid
1 2
2 2
3 1
4 1

"project"
Project table, that we can refer to with projectid

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

projectid name
1 ring
2 lord

"deparment"
Our deparment table which we can refer to with empid

empid deparment
1 1
2 1
3 2
4 3

I’ve been attepting to make a single querry that can do this. Right now I have a found a way to output the number of deparments working on a project, but I still need to get the name of the project to output. Any suggestions would help.

SELECT count(DISTINCT d.deprment)
FROM employeeproject ep
LEFT JOIN project p
on p.projid = ep.projid
LEFT JOIN deparment d
on ep.empid = d.empid
group by p.projid;

Expected result :

project name
Lord

>Solution :

You can use an aggregation on the project name while using count of different departments equal to 1 as condition in an HAVING clause.

SELECT name
FROM       project p
INNER JOIN employeeproject ep
        ON p.projectid = ep.projectid
INNER JOIN department d
        ON ep.empid = d.empid
GROUP BY name
HAVING COUNT(DISTINCT d.deparment) = 1

Here’s a demo in MySQL, though this should work on most DBMS’.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading