I'm using sql-server. I have 2 tables an employee table and a comments table. The employee table lists the employee and their manager. When a manager gives an employee their annual review, they put a comment into the comments table of a certain type.
I want a list of managers along with a total count of employees for that manager and then a third column that lists a count of employees for which the manager has put a comment of a certain type into the comments table after a certain date.
This gets me a list of managers and total number of employees:
select manager, count(*) as total_employees
from employee
where
is_active='Y'
and manager is not null
group by manager
manager | total_employees |
---|---|
jones | 7 |
smith | 3 |
johnson | 15 |
nelson | 14 |
That works. Now, I need to find each employee in the comments table and count how many employees have a comment of a certain type. What I'm looking for is
manager | total_employees | completed |
---|---|---|
jones | 7 | 3 |
smith | 3 | 3 |
johnson | 15 | 10 |
nelson | 14 | 0 |
select manager, count(employee.id) as total_employees, count(comments) as completed
from employee
join comments on comments.parent_row_id=employee.id
where
is_active='Y'
and manager is not null
and comments.comment_type_id='REVIEW'
and comments.entered_date > '11/01/2022'
group by manager
The above query gives me:
manager | total_employees | completed |
---|---|---|
jones | 5 | 5 |
johnson | 1 | 1 |
If there's no comment in the comments table, it leaves the manager out entirely and the total_employees is now a count of employees with comments instead of total count of employees for the manager.