[Leetcode 1050] Actors and Directors Who Cooperated At Least Three Times

原题说明

Table: ActorDirector

+————-+———+
| Column Name | Type |
+————-+———+
| actor_id | int |
| director_id | int |
| timestamp | int |
+————-+———+
timestamp is the primary key column for this table.

 

Write a SQL query for a report that provides the pairs (actor_id, director_id) where the actor have cooperated with the director at least 3 times.

Example:

ActorDirector table:
+————-+————-+————-+
| actor_id | director_id | timestamp |
+————-+————-+————-+
| 1 | 1 | 0 |
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 1 | 2 | 3 |
| 1 | 2 | 4 |
| 2 | 1 | 5 |
| 2 | 1 | 6 |
+————-+————-+————-+

Result table:
+————-+————-+
| actor_id | director_id |
+————-+————-+
| 1 | 1 |
+————-+————-+
The only pair is (1, 1) where they cooperated exactly 3 times.

解题思路

我们需要找出一起至少合作过3次的演员和导演。

  1. 对二元组(演员,导演)分组,分别计算每组个数,选出每组个数>=3的行。
  2. 这里我们需要应用group by语法和count函数。

示例代码 (mysql)

1
2
3
4
SELECT A.actor_id, A.director_id
FROM ActorDirector AS A
GROUP BY A.actor_id, A.director_id
HAVING COUNT(*) >= 3;

归纳总结

我们在Youtube上更新了视频讲解,欢迎关注!

------ 关注公众号:猩猩的乐园 ------