MySQL 1731.sql
SELECT m.employee_id,
m.name,
COUNT(*) AS reports_count,
ROUND(AVG(e.age)) AS average_age
FROM Employees m, Employees e
WHERE m.employee_id = e.reports_to
GROUP BY m.employee_id
ORDER BY m.employee_id
Difficulty
and has an acceptance rate of about 54% (700k+ submissions).
Typical patterns to solve this problem:
- Database
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The query extracts managerial information from an Employees table that stores both employee records and hierarchical relationships. For each manager, identified by employee_id, the statement returns the manager’s identifier, name, the total number of direct reports, and the rounded average age of those reports. The result set is ordered by the manager’s identifier, providing a deterministic sequence.
Key Steps
The first step establishes two aliases for the same table: m represents a potential manager and e represents an employee who may report to that manager. The WHERE clause links the two aliases through the condition m.employee_id = e.reports_to, ensuring that only rows where an employee reports directly to the manager are considered.
FROM Employees m, Employees e
WHERE m.employee_id = e.reports_to
Next, the SELECT list gathers the manager’s identifier and name directly from the m alias. The COUNT(*) aggregate counts every row that satisfies the join condition, yielding the number of direct reports for each manager.
SELECT m.employee_id,
m.name,
COUNT(*) AS reports_count,
The AVG(e.age) aggregate computes the mean age of the reports, and ROUND rounds the result to the nearest integer, producing a clean, whole-number average.
ROUND(AVG(e.age)) AS average_age
The GROUP BY clause groups rows by the manager’s identifier, which implicitly groups by the manager’s name as well because the name is functionally dependent on the identifier. This grouping enables the aggregates to be calculated per manager.
GROUP BY m.employee_id
Finally, the ORDER BY clause sorts the output by the manager’s identifier, guaranteeing a predictable ordering of rows.
ORDER BY m.employee_id
Edge Cases Handled
When a manager has no direct reports, the join condition eliminates that manager from the result set because there are no matching rows in the e alias. Consequently, the query naturally excludes managers without reports, avoiding a division-by-zero scenario in the average age calculation.
If an employee’s reports_to column contains a null value, that employee does not satisfy the join condition, and therefore does not affect any manager’s aggregates. This behavior prevents null references from contaminating the counts or averages.
In the event that the age column contains null values for some reports, the AVG function automatically ignores those nulls, ensuring that the average age reflects only known ages. The ROUND function then operates on the resulting non-null average.
Performance Optimizations
The query leverages a self-join on the primary key (employee_id) and the foreign key (reports_to). When an index exists on employee_id (typically the primary key) and an index exists on reports_to, the database engine can efficiently locate matching rows for each manager, reducing the cost of the join operation.
The use of COUNT(*) avoids the overhead of counting a specific column, allowing the engine to use a simple row count during aggregation.
Aggregating directly within the grouped result set (COUNT(*) and AVG(e.age)) eliminates the need for additional subqueries or temporary tables, keeping the execution plan compact.
Sorting is performed on the grouped identifier, which is already the grouping key. Many database systems can produce the grouped rows in sorted order without a separate sorting step, further streamlining the final ordering.
Overall, the query’s structure-simple join, direct aggregation, and ordering on the grouping key-aligns well with typical relational engine optimizations, delivering efficient execution for typical employee hierarchies.
ELI5 - Simplified Explanation
Imagine a big school where some teachers have students who report to them. This code is like a helper looking through a giant list of everyone in the school. First, it finds the teachers and then looks for all the students who report to each one. Once it matches the students to their teacher, it counts up how many students each teacher has. After that, it takes the ages of all those students and does some math to find out the average age. Finally, it puts all the teachers in order by their identification numbers so the list is neat and tidy.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||
|---|---|---|---|---|---|---|
| author | solutions | |||||
| www | AlgoMonster | C++ | Java | Python | TS | |
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| Progiez | C++ | Java | Python | |||
| github | suxrobGM | SQL | ||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| Progiez | C++, Java, Python | |||||
| suxrobGM | SQL |
Videos
Solved On The Same Day
- problem 415: Add Strings
- problem 463: Island Perimeter
- problem 541: Reverse String II
- problem 1211: Queries Quality and Percentage
- problem 1251: Average Selling Price
- problem 1280: Students and Examinations
- problem 1327: List the Products Ordered in a Period
- problem 1378: Replace Employee ID With The Unique Identifier
- problem 1407: Top Travellers
- problem 1484: Group Sold Products By The Date
- problem 1517: Find Users With Valid E-Mails
- problem 1527: Patients With a Condition
- problem 1581: Customer Who Visited but Did Not Make Any Transactions
- problem 1587: Bank Account Summary II
- problem 1633: Percentage of Users Attended a Contest
- problem 1661: Average Time of Process per Machine
- problem 1667: Fix Names in a Table
- problem 1683: Invalid Tweets
- problem 1693: Daily Leads and Partners
- problem 1729: Find Followers Count
- problem 1741: Find Total Time Spent by Each Employee
- problem 1757: Recyclable and Low Fat Products
- problem 1789: Primary Department for Each Employee
- problem 1795: Rearrange Products Table
- problem 1873: Calculate Special Bonus
- problem 1890: The Latest Login in 2020
- problem 1965: Employees With Missing Information
- problem 1978: Employees Whose Manager Left the Company
- problem 2356: Number of Unique Subjects Taught by Each Teacher
- problem 166: Fraction to Recurring Decimal
- problem 223: Rectangle Area
- problem 240: Search a 2D Matrix II
- problem 318: Maximum Product of Word Lengths
- problem 357: Count Numbers with Unique Digits
- problem 394: Decode String
- problem 1158: Market Analysis I
- problem 1341: Movie Rating
- problem 1492: The kth Factor of n
- problem 1498: Number of Subsequences That Satisfy the Given Sum Condition
- problem 1907: Count Salary Categories
- problem 1934: Confirmation Rate
- problem 2405: Optimal Partition of String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality