返回介绍

solution / 1300-1399 / 1303.Find the Team Size / README_EN

发布于 2024-06-17 01:03:21 字数 2942 浏览 0 评论 0 收藏 0

1303. Find the Team Size

中文文档

Description

Table: Employee

+---------------+---------+
| Column Name   | Type  |
+---------------+---------+
| employee_id   | int   |
| team_id     | int   |
+---------------+---------+
employee_id is the primary key (column with unique values) for this table.
Each row of this table contains the ID of each employee and their respective team.

 

Write a solution to find the team size of each of the employees.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Employee Table:
+-------------+------------+
| employee_id | team_id  |
+-------------+------------+
|   1     |   8    |
|   2     |   8    |
|   3     |   8    |
|   4     |   7    |
|   5     |   9    |
|   6     |   9    |
+-------------+------------+
Output: 
+-------------+------------+
| employee_id | team_size  |
+-------------+------------+
|   1     |   3    |
|   2     |   3    |
|   3     |   3    |
|   4     |   1    |
|   5     |   2    |
|   6     |   2    |
+-------------+------------+
Explanation: 
Employees with Id 1,2,3 are part of a team with team_id = 8.
Employee with Id 4 is part of a team with team_id = 7.
Employees with Id 5,6 are part of a team with team_id = 9.

Solutions

Solution 1: Group By + Equi-Join

We can first count the number of people in each team and record it in the T table. Then, we can use an equi-join to join the Employee table and the T table based on team_id, and obtain the total number of people in each team.

# Write your MySQL query statement below
WITH
  T AS (
    SELECT team_id, COUNT(1) AS team_size
    FROM Employee
    GROUP BY 1
  )
SELECT employee_id, team_size
FROM
  Employee
  JOIN T USING (team_id);

Solution 2: Left Join

We can also use a left join to join the Employee table with itself based on team_id, and then group by employee_id to count the total number of people in each team that the employee belongs to.

# Write your MySQL query statement below
SELECT e1.employee_id, COUNT(1) AS team_size
FROM
  Employee AS e1
  LEFT JOIN Employee AS e2 USING (team_id)
GROUP BY 1;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文