Show each department name, number of employees, and total order value for employees in that department.
Problem Statement
Examples
Input: departments table: +----+-------+ | id | name | +----+-------+ | 1 | IT | | 2 | HR | | 3 | Sales | +----+-------+ employees table: +----+---------+---------+ | id | name | dept_id | +----+---------+---------+ | 1 | Alice | 1 | | 2 | Bob | 1 | | 3 | Charlie | 2 | | 4 | Dana | 3 | +----+---------+---------+ orders table: +-----+-------------+--------+ | id | employee_id | amount | +-----+-------------+--------+ | 101 | 1 | 500 | | 102 | 1 | 300 | | 103 | 2 | 400 | | 104 | 3 | 200 | | 105 | 4 | 600 | +-----+-------------+--------+
Output: +------------+-----------+--------------+ | department | emp_count | total_orders | +------------+-----------+--------------+ | IT | 2 | 1200 | | Sales | 1 | 600 | | HR | 1 | 200 | +------------+-----------+--------------+
Explanation: The query joins the matching records on the related keys and projects the requested fields.
Complexity
Time Complexity: -
Space Complexity: -
Hints
Editorial & Approach
Problem Overview & Intuition
To solve "Complex Multi-Join Aggregate Report", we query the relational database engine using declarative SQL. The goal is to show each department name, number of employees, and total order value for employees in that department. By formulating an optimal execution plan with appropriate projection and filtering, the database engine executes the query with minimal overhead.
Step-by-Step Approach
- Analyze Schema: Identify the target tables, necessary foreign keys, and expected output columns.
- Construct Filtering & Logic: Apply table joins to isolate the requested data.
- Format & Order: Sort the resulting records according to specified order criteria.
Optimal Implementation (SQL)
SELECT d.name AS department, COUNT(DISTINCT e.id) AS emp_count, COALESCE(SUM(o.amount), 0) AS total_orders FROM departments d LEFT JOIN employees e ON d.id = e.dept_id LEFT JOIN orders o ON e.id = o.employee_id GROUP BY d.name ORDER BY total_orders DESC;
Complexity Analysis
Key Considerations & Edge Cases
- Empty Tables: The query executes safely returning zero rows without syntax error.
- NULL Values: Columns containing NULL values are properly handled by standard ANSI SQL semantics.
- Case Sensitivity: String comparisons and keywords adhere to PostgreSQL/standard SQL rules.