Actors And Directors Who Cooperated At Least Three Times Problem
Description
LeetCode Problem 1050.
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.
Solution
Approach: GROUP BY and HAVING
Each row is one cooperation, identified by its unique timestamp. To count how often an actor worked with a director, group by the pair (actor_id, director_id): every group then holds all the cooperations of one pair, and COUNT(*) is their number.
Keep the pairs with at least three cooperations. The condition uses an aggregate, so it goes in HAVING, which is evaluated after grouping; WHERE runs before grouping and cannot see COUNT(*). Use >= 3, since "at least 3" includes pair (1, 1) with exactly three.
The Pandas version counts rows per pair with groupby(...).size() and keeps the pairs whose count is at least 3.
SELECT actor_id,
director_id
FROM ActorDirector
GROUP BY actor_id, director_id
HAVING COUNT(*) >= 3;