LeetCode-1303. The number of teams seeking (simple)

Employees Table: Employee

+ --------- + --------------- +
| Column the Name | Type |
+ --------------- + + ---------
| employee_id | int |
| team_id | int |
+ --------------- + --------- +
employee_id field is the primary key of this table, for each row in the table contains each employee's ID and the team to which they belong.
Write a SQL query to obtain each employee where the total number of teams.

The order of query results without specific requirements.

Query Result Format examples are as follows:

Employee Table:
+-------------+------------+
| employee_id | team_id    |
+-------------+------------+
|     1       |     8      |
|     2       |     8      |
|     3       |     8      |
|     4       |     7      |
|     5       |     9      |
|     6       |     9      |
+-------------+------------+
Result table:
+-------------+------------+
| employee_id | team_size  |
+-------------+------------+
|     1       |     3      |
|     2       |     3      |
|     3       |     3      |
|     4       |     1      |
|     5       |     2      |
|     6       |     2      |
+ ------------ + ------------- +
ID is 1, 2, as a member of the team staff is team_id 8,
ID of 4 employees are team_id for the team of 7 members,
ID 5, 6 employees as members of the team are team_id 9.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/find-the-team-size
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Moderation: to write a SQL query to obtain each employee where the total number of teams.

Thoughts: Query behind team id id summation.

Problem solving:

select employee_id,
    (select count(*) from Employee e2
        where e1.team_id = e2.team_id) as team_size
from Employee e1
-- 练习
select employee_id (select count(*) from Employee e2 
where e1.team_id = e2.team_id)as team_size
from Employee e1;

Method two: left join

select e1.employee_id, count(*) team_size
from employee e1 left join employee e2
on e1.team_id = e2.team_id
group by e1.employee_id;
-- 通过left join
select e1.employee_id,count(*) team_size
from employee e1 left join employee e2
on e1.team_id = e2.team_id
group by e1.employee_id;

 Knowledge points:

Published 144 original articles · won praise 2 · Views 5735

Guess you like

Origin blog.csdn.net/Hello_JavaScript/article/details/104781700