Fast and Simple Solution by using window func with description
Problem Statement\nGiven two tables Employee and Department with columns id, name, and salary in the Employee table, and id and name in the Department table, th
# Problem Statement\nGiven two tables `Employee` and `Department` with columns `id`, `name`, and `salary` in the `Employee` table, and `id` and `name` in the `Department` table, the task is to retrieve the top salaried employee from each department.\n\n## Intuition\nThe problem involves selecting the top salaried employee from each department based on the salary.\n\n## Approach\n1. **Use of Window Function (`DENSE_RANK`):**\n   - Utilize the window function `DENSE_RANK` along with the `OVER` clause to rank employees within each department based on their salary.\n   - Partition the data by `department.id` and order it by `employee.salary` in descending order.\n   - The resulting column, named `rnk`, will represent the dense ranking of employees within each department based on salary.\n\n2. **Filtering Top Salaried Employees:**\n   - Create a subquery (`t`) to represent the combined result set.\n   - Use the outer query to filter out rows where `rnk` is equal to 1, indicating the top-salaried employee in each department.\n\n3. **Result Output:**\n   - Select the columns `Department`, `Employee`, and `Salary` for the final result.\n\n## Complexity\n- **Time complexity:**\n  - The time complexity is primarily determined by the use of the window function `DENSE_RANK` and the sorting operation specified by the `ORDER BY` clause. It is generally efficient and can be considered as $$O(n \\log n)$$, where $$n$$ is the total number of rows in the `Employee` table.\n\n- **Space complexity:**\n  - The space complexity is $$O(n)$$, where $$n$$ is the total number of rows in the `Employee` table. This accounts for the storage of intermediate results during the calculation of the dense rank.\n\n# Code\n```\n# Write your MySQL query statement below\nSELECT \n    Department,\n    Employee,\n    Salary\nFROM (SELECT \n    d.name AS Department,\n    e.name AS Employee,\n    e.salary AS Salary,\n    DENSE_RANK() OVER (PARTITION BY d.id ORDER BY e.salary DESC) AS rnk\nFROM Employee e\nJOIN Department d\nON e.departmentId = d.id) AS t\nWHERE rnk = 1;\n```\n![img.png](https://assets.leetcode.com/users/images/f0e1d605-7fac-49e1-8cb8-7e8c96e5a8dd_1703409914.067328.png)\n\n
['MySQL']