1
SELECT pnumber, pname, COUNT(*)
FROM project 
INNER JOIN works_on ON pno=pnumber 
INNER JOIN department ON dnumber=dnum
GROUP BY pnumber

Right now, mysql will return the project number and name, along with the number of employees who are working on it. What I want to do is that mysql only count employees from department 5. In other words there are people from different departments working on projects, but I want only the ones from department 5 to be counted and not all.

3
  • 2
    Isn't that what WHERE clauses are for? Commented Nov 3, 2013 at 8:44
  • Nope, if I use where, it only returns results from projects in department 5. I want projects from all departments, but employee count only from department 5. Commented Nov 3, 2013 at 8:49
  • Then you're using the wrong column in the WHERE clause. It would help if you showed the schema. Why do projects have department numbers? People are in departments, projects aren't. Commented Nov 3, 2013 at 8:51

3 Answers 3

2

If Barmar's and Shafeeq's suggestion of using a WHERE clause won't work for you (for example, if you need to include all departments in your result, but only count people from department 5) you can use this:

 SUM(IF(dnum=5, 1, 0)) AS CountFromDepartment5

So we'd have:

SELECT pnumber, pname, COUNT(*) AS TotalCount,  SUM(IF(dnum=5, 1, 0)) AS CountFromDepartment5
FROM project 
INNER JOIN works_on ON pno=pnumber 
INNER JOIN department ON dnumber=dnum
GROUP BY pnumber
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This is just the way I want it. I was trying to use count just by itself, that's why I couldn't make it work.
2

You can use WHERE

SELECT pnumber, pname, COUNT(*)
FROM project 
JOIN works_on ON pno = pnumber 
JOIN department ON dnumber=dnum
WHERE dnumber = 5
GROUP BY pnumber

EDIT

SELECT pnumber, pname, COUNT(*),SUM(IF(dnumber=5, 1, 0)) AS count5 
FROM project 
JOIN works_on ON pno = pnumber 
JOIN department ON dnumber=dnum
GROUP BY pnumber

1 Comment

I have already tried that, if I use where, it only returns results from projects in department 5. I want projects from all departments, but employee count only from department 5.
0

Use a WHERE clause that specifies the department you want.

SELECT pnumber, pname, COUNT(*)
FROM project 
INNER JOIN works_on ON pno=pnumber 
WHERE dnumber = 5
GROUP BY pnumber

You don't need to join with department, since the department number also exists as a foreign key in the works_on table.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.