Similar Problems

Similar Problems not available

Group Employees Of The Same Salary - Leetcode Solution

Companies:

LeetCode:  Group Employees Of The Same Salary Leetcode Solution

Difficulty: Medium

Topics: database  

Problem:

Given a table with employee information including salary, write a SQL query to group all employees of the same salary together and order them in a non-descending order.

Table: Employee

| Column Name | Type | | --- | --- | | Id | Integer | | Name | String | | Salary | Integer |

Solution:

To solve the Group Employees Of The Same Salary problem on leetcode, we need to group all employees of the same salary together and order them in a non-descending order. We can use the following SQL query to achieve this:

SELECT Salary, GROUP_CONCAT(Name ORDER BY Name) AS Employees 
FROM Employee 
GROUP BY Salary 
ORDER BY Salary;

Explanation:

We use the SELECT statement to select the salary and the GROUP_CONCAT function to group all the employees with the same salary together and order them in a non-descending order by their names.

The GROUP BY clause is used to group all the employees with the same salary together. The ORDER BY clause is used to order all the groups in a non-descending order by their salaries.

The GROUP_CONCAT function concatenates all the employee names into a single string separated by a comma. The ORDER BY clause within the GROUP_CONCAT function is used to order all the employee names within a group in a non-descending order by their names.

Finally, the resulting table contains two columns: Salary and Employees. The Salary column contains all the unique salaries in ascending order and the Employees column contains all the employees with the same salary grouped together and ordered in a non-descending order by their names.

Example:

Suppose we have the following table Employee:

| Id | Name | Salary | | --- | --- | --- | | 1 | John | 50000 | | 2 | Bob | 50000 | | 3 | Alice | 60000 | | 4 | Jane | 70000 |

The SQL query:

SELECT Salary, GROUP_CONCAT(Name ORDER BY Name) AS Employees 
FROM Employee 
GROUP BY Salary 
ORDER BY Salary;

will output:

| Salary | Employees | | --- | --- | | 50000 | Bob,John | | 60000 | Alice | | 70000 | Jane |

In the above example, two employees (John and Bob) have the same salary of 50000, so they are grouped together and their names are concatenated into a single string separated by a comma. The other employees are not grouped because they have unique salaries.

Group Employees Of The Same Salary Solution Code

1