devxlogo

using COUNT and GROUP BY with zero-values

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.

See also  Does It Make Sense to Splurge on a Laptop?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist