Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ Have a good contributing!
- [1683. Invalid Tweets](./leetcode/easy/1683.%20Invalid%20Tweets.sql)
- [1693. Daily Leads and Partners](./leetcode/easy/1693.%20Daily%20Leads%20and%20Partners.sql)
- [1729. Find Followers Count](./leetcode/easy/1729.%20Find%20Followers%20Count.sql)
- [1731. The Number of Employees Which Report to Each Employee](./leetcode/easy/1731.%20The%20Number%20of%20Employees%20Which%20Report%20to%20Each%20Employee.sql)
- [1741. Find Total Time Spent by Each Employee](./leetcode/easy/1741.%20Find%20Total%20Time%20Spent%20by%20Each%20Employee.sql)
- [1789. Primary Department for Each Employee](./leetcode/easy/1789.%20Primary%20Department%20for%20Each%20Employee.sql)
- [1965. Employees With Missing Information](./leetcode/easy/1965.%20Employees%20With%20Missing%20Information.sql)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
Question 1731. The Number of Employees Which Report to Each Employee
Link: https://leetcode.com/problems/the-number-of-employees-which-report-to-each-employee/description/?envType=study-plan-v2&envId=top-sql-50

Table: Employees

+-------------+----------+
| Column Name | Type |
+-------------+----------+
| employee_id | int |
| name | varchar |
| reports_to | int |
| age | int |
+-------------+----------+
employee_id is the column with unique values for this table.
This table contains information about the employees and the id of the manager they report to. Some employees do not report to anyone (reports_to is null).


For this problem, we will consider a manager an employee who has at least 1 other employee reporting to them.

Write a solution to report the ids and the names of all managers, the number of employees who report directly to them, and the average age of the reports rounded to the nearest integer.

Return the result table ordered by employee_id.
*/

SELECT
e.employee_id,
e.name,
(
SELECT COUNT(1)
FROM Employees AS e1
WHERE e1.reports_to = e.employee_id
) AS reports_count,
(
SELECT ROUND(AVG(e2.age)::numeric)
FROM Employees AS e2
WHERE e2.reports_to = e.employee_id
) AS average_age
FROM Employees AS e
WHERE (
SELECT COUNT(1)
FROM Employees AS e1
WHERE e1.reports_to = e.employee_id
) > 0
ORDER BY e.employee_id ASC