leetcode-mysql 2021-06-03

该博客介绍了一个SQL查询问题,目标是根据员工的薪资将他们分组到团队中,确保每个团队的成员薪资相同且至少有两名员工。解题思路涉及到了`GROUP BY`和`HAVING`子句以及`DENSE_RANK()`函数。查询首先找出薪资至少有两个员工的薪资值,然后为这些薪资值分配团队ID,最后返回员工的详细信息及其所属团队ID。
摘要由CSDN通过智能技术生成

来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/group-employees-of-the-same-salary 【侵删】

 

ExampleA(Group Employees of the Same Salary)

Table: Employees

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| employee_id | int     |
| name        | varchar |
| salary      | int     |
+-------------+---------+


employee_id is the primary key for this table.
Each row of this table indicates the employee ID, employee name, and salary.
 

A company wants to divide the employees into teams such that all the members on each team have the same salary. The teams should follow these criteria:

Each team should consist of at least two employees.
All the employees on a team should have the same salary.
All the employees of the same salary should be assigned to the same team.
If the salary of an employee is unique, we do not assign this employee to any team.
A team's ID is assigned based on the rank of the team's salary relative to the other teams' salaries, where the team with the lowest salary has team_id = 1. Note that the salaries for employees not on a team are not included in this ranking.
Write an SQL query to get the team_id of each employee that is in a team.

Return the result table ordered by team_id in ascending order. In case of a tie, order it by employee_id in ascending order.

The query result format is in the following example:

 

Employees table:
+-------------+---------+--------+
| employee_id | name    | salary |
+-------------+---------+--------+
| 2           | Meir    | 3000   |
| 3           | Michael | 3000   |
| 7           | Addilyn | 7400   |
| 8           | Juan    | 6100   |
| 9           | Kannon  | 7400   |
+-------------+---------+--------+
Result table:
+-------------+---------+--------+---------+
| employee_id | name    | salary | team_id |
+-------------+---------+--------+---------+
| 2           | Meir    | 3000   | 1       |
| 3           | Michael | 3000   | 1       |
| 7           | Addilyn | 7400   | 2       |
| 9           | Kannon  | 7400   | 2       |
+-------------+---------+--------+---------+

解题思路(group by having count(salary)>=2; dense_rank() over())

select employee_id,name,salary, dense_rank() over (order by salary) team_id from employees where salary in (select salary from employees group by salary having count(salary)>=2);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值