using COUNT and GROUP BY with zero-values

Question:
I’m trying to query our Human Resources database to find the number of temporary employees in each department. I’m using the following SQL statement:

select count (*)from employeewhere status = 'Temporary'group by departments;

I expect the following results:

3004202

but am getting:

3422

That is, the zero-count departments are not in my results. Is there a way to specify that I want the zeros returned, too?

Answer:
Using SQL Server you need add only one more word to obtain the desired result. Change the group by departments to group by ALL departments. The “all” keyword tells SQL Server to return all departments, even those with a count of 0.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: