Ranking Top Actors Across Shared Entity IDs

Medium · Data Manipulation (SQL/Python) · Software Engineer · Onsite

Problem Statement

Implement top_10_popular_actors(objects, credits) to rank the ten actors who have acted in the largest number of distinct films across a unified catalog.

Both films and individuals are stored together in a single objects collection sharing one object_id keyspace:

  • objects — entity dictionaries with keys:
    • object_id (int): unique identifier across the entire catalog.
    • object_type (str): 'movie' or 'person'.
    • name (str): film title or person's display name.
  • credits — billing dictionaries with keys:
    • movie_object_id (int): target film identifier.
    • person_object_id (int): target person identifier.
    • role (Optional[str]): billing label such as 'actor', 'director', 'writer', or None.

Catalog data may contain unnormalized strings, duplicate rows, and broken references, so apply all of the following rules:

  1. Role normalization: A credit qualifies as an acting credit if and only if role is a string whose whitespace-trimmed, lowercase value equals 'actor' (for example, 'actor', 'Actor', and ' ACTOR ' count, whereas 'director', '', and None do not).
  2. Entity type verification: Keep a credit only when movie_object_id exists in objects with object_type == 'movie' and person_object_id exists in objects with object_type == 'person'. Drop credits referencing missing IDs or IDs of the wrong object_type.
  3. Distinct film count: A person's movie_count equals the number of distinct valid movie_object_ids on which they hold at least one valid acting credit. Multiple acting rows (or extra directing/writing rows) for the same (person_object_id, movie_object_id) pair still count that film only once.
  4. Filtering and ranking: Exclude people with 0 valid acting films. Sort qualifying actors by movie_count descending, breaking ties by person_object_id ascending (numeric order), and return at most the first 10 records as dictionaries with keys person_object_id, name, and movie_count.

Examples

Example 1

Input:

objects = [
    {"object_id": 10, "object_type": "movie", "name": "Harbor Light"},
    {"object_id": 20, "object_type": "movie", "name": "Glass Orbit"},
    {"object_id": 30, "object_type": "movie", "name": "Night Train"},
    {"object_id": 501, "object_type": "person", "name": "Nora"},
    {"object_id": 502, "object_type": "person", "name": "Owen"},
    {"object_id": 503, "object_type": "person", "name": "Pia"},
]
credits = [
    {"movie_object_id": 10, "person_object_id": 501, "role": "actor"},
    {"movie_object_id": 10, "person_object_id": 501, "role": "director"},
    {"movie_object_id": 10, "person_object_id": 501, "role": "actor"},
    {"movie_object_id": 20, "person_object_id": 501, "role": "actor"},
    {"movie_object_id": 30, "person_object_id": 502, "role": "actor"},
    {"movie_object_id": 10, "person_object_id": 503, "role": "director"},
]

Output:

[
    {"person_object_id": 501, "name": "Nora", "movie_count": 2},
    {"person_object_id": 502, "name": "Owen", "movie_count": 1},
]

Explanation: Nora (501) has two 'actor' rows and one 'director' row on film 10 plus one 'actor' row on film 20, giving 2 distinct films ({10, 20}). Owen (502) acted in film 30 (1 film). Pia (503) only directed, so she is omitted.

Example 2

Input:

objects = [
    {"object_id": 1, "object_type": "movie", "name": "Red Dune"},
    {"object_id": 2, "object_type": "movie", "name": "Cold Peak"},
    {"object_id": 40, "object_type": "person", "name": "Tariq"},
    {"object_id": 8, "object_type": "person", "name": "Sana"},
    {"object_id": 15, "object_type": "person", "name": "Vera"},
]
credits = [
    {"movie_object_id": 1, "person_object_id": 40, "role": "ACTOR"},
    {"movie_object_id": 2, "person_object_id": 40, "role": "  Actor "},
    {"movie_object_id": 1, "person_object_id": 8, "role": "actor"},
    {"movie_object_id": 2, "person_object_id": 8, "role": "actor"},
    {"movie_object_id": 1, "person_object_id": 15, "role": "writer"},
    {"movie_object_id": 2, "person_object_id": 15, "role": None},
]

Output:

[
    {"person_object_id": 8, "name": "Sana", "movie_count": 2},
    {"person_object_id": 40, "name": "Tariq", "movie_count": 2},
]

Explanation: After trimming whitespace and case-folding, 'ACTOR' and ' Actor ' both count as 'actor'. Sana (8) and Tariq (40) tie at 2 films, so smaller person_object_id (8 < 40) places Sana first. Vera (15) has zero acting credits.

Example 3

Input:

objects = [
    {"object_id": 50, "object_type": "movie", "name": "Silent Reef"},
    {"object_id": 60, "object_type": "person", "name": "Leo"},
]
credits = [
    {"movie_object_id": 50, "person_object_id": 60, "role": "actor"},
    {"movie_object_id": 404, "person_object_id": 60, "role": "actor"},
    {"movie_object_id": 50, "person_object_id": 50, "role": "actor"},
    {"movie_object_id": 60, "person_object_id": 60, "role": "actor"},
]

Output:

[{"person_object_id": 60, "name": "Leo", "movie_count": 1}]

Explanation: Only (50, 60, 'actor') links a 'movie' to a 'person'. ID 404 does not exist in objects, (50, 50) places a 'movie' ID in person_object_id, and (60, 60) places a 'person' ID in movie_object_id.

Constraints

  • 0 <= len(objects) <= 10^5
  • 0 <= len(credits) <= 2 * 10^5
  • Every object_id in objects is a unique integer, and object_type is 'movie' or 'person'.
  • role in credits is a string or None.
  • If fewer than 10 qualifying actors exist, return all of them in ranked order.

Step-by-step walkthrough

  1. Pin down the rules and spot the data traps

    We receive two collections—represented as relational tables in SQL or lists of dictionaries in Python:

    • objects: object_id, object_type ('movie' or 'person'), and name. Crucially, films and people share one object_id catalog.
    • credits: movie_object_id, person_object_id, and role. A person can appear in multiple rows for the same film (such as both 'actor' and 'director', or repeated 'actor' rows).

    Before writing code, confirm the four edge rules reflected in the specification and examples:

    1. Popularity metric: movie_count equals the count of distinct valid films where a person holds at least one acting credit. People with zero qualifying acting credits are excluded.
    2. Cutoff and tie-breaker: Return up to 10 records sorted by movie_count descending, then person_object_id ascending. (We also show the SQL variant that retains everyone tied at 10th place.)
    3. Unnormalized role strings: Example 2 passes 'ACTOR', ' Actor ', 'writer', and None, counting 'ACTOR' and ' Actor ' as acting credits. Strip surrounding whitespace and lower-case strings before checking == 'actor'.
    4. Dangling or wrong-type IDs: Example 3 includes a credit pointing to missing ID 404, a credit placing film 50 inside person_object_id, and a credit placing person 60 inside movie_object_id. Every endpoint must exist and match its expected object_type.
  2. Why counting credit rows directly goes wrong

    Two traps corrupt a naive GROUP BY person_object_id aggregation:

    Trap 1 — Row inflation from multiple roles and repeated acting rows. Look at Example 1 (Harbor Light = 10, Glass Orbit = 20, Night Train = 30):

    Person    Credits in input                                   All rows  Actor rows  Distinct actor films
    --------  -------------------------------------------------  --------  ----------  --------------------
    501 Nora  (10,actor), (10,director), (10,actor), (20,actor)  4         3           2  (films 10, 20)
    502 Owen  (30,actor)                                         1         1           1  (film 30)
    503 Pia   (10,director)                                      1         0           0  (excluded!)
    
    • Raw COUNT(*) gives Nora 4 and includes Pia (1), who never acted in any film.
    • Filtering to 'actor' and running COUNT(*) still gives Nora 3 because (10, 501, 'actor') appears twice.
    • Filtering to valid acting rows first and taking COUNT(DISTINCT movie_object_id) yields the true count of 2.

    Trap 2 — Shared object_id keyspace. Because films and people reside in one objects table, an ID like 50 exists in objects—as a 'movie'!

    objects:  [50, 'movie', 'Silent Reef']   [60, 'person', 'Leo']
    
    bad credit A: movie_object_id = 404, person_object_id = 60   -> 404 missing from objects!
    bad credit B: movie_object_id = 50,  person_object_id = 50   -> 50 exists, but 50 is 'movie', not 'person'!
    bad credit C: movie_object_id = 60,  person_object_id = 60   -> 60 exists, but 60 is 'person', not 'movie'!
    

    Joining credits to objects on person_object_id alone—or skipping object_type—lets bad credit A count nonexistent film 404 and lets bad credit B rank 'Silent Reef' as an actor! We must verify both endpoints against objects with m.object_type = 'movie' and p.object_type = 'person'.

  3. Write the SQL aggregation

    Putting both safeguards into SQL produces a clean, single-query solution:

    SELECT c.person_object_id,
           p.name,
           -- Count each valid film at most once per actor, even when actor rows repeat.
           COUNT(DISTINCT c.movie_object_id) AS movie_count
    FROM credits AS c
    -- Join 1: verify movie_object_id exists AND has object_type = 'movie'.
    JOIN objects AS m
      ON m.object_id = c.movie_object_id
     AND m.object_type = 'movie'
    -- Join 2: verify person_object_id exists AND has object_type = 'person' (and read name).
    JOIN objects AS p
      ON p.object_id = c.person_object_id
     AND p.object_type = 'person'
    -- Normalize whitespace and casing; NULL evaluates to UNKNOWN and is discarded.
    WHERE LOWER(TRIM(c.role)) = 'actor'
    GROUP BY c.person_object_id, p.name
    -- Deterministic tie-break by smaller person_object_id before slicing at 10.
    ORDER BY movie_count DESC, c.person_object_id ASC
    LIMIT 10;
    
  4. Build the Python lookup tables and per-actor film sets

    In Python, we implement the exact same logic using dictionaries and sets:

    1. Scan objects once to populate type_of and name_of. Calling type_of.get(id) returns None for missing IDs, so missing IDs and wrong-type IDs fail the exact same != "movie" / != "person" check.
    2. For each credit whose normalized role equals "actor" and whose endpoints pass both type checks, insert movie_id into movies_of[person_id]—a set that automatically deduplicates repeated movie_ids.
    def normalize_role(label: object) -> Optional[str]:
        """Trim whitespace and lower-case a role string like ' Actor '; non-strings return None."""
        if not isinstance(label, str):
            return None
        return label.strip().lower()
    
    
    # Phase 1: Index objects by ID so we can verify each ID's type and look up person names in O(1) time.
    # Movies and people share the same object_id space, so every join must check object_type.
    # type_of: maps object_id -> 'movie' or 'person', e.g. {10: 'movie', 501: 'person'}.
    # name_of: maps object_id -> display name string, e.g. {10: 'Harbor Light', 501: 'Nora'}.
    type_of: Dict[object, object] = {}
    name_of: Dict[object, object] = {}
    for obj in objects:
        object_id = obj["object_id"]
        type_of[object_id] = obj["object_type"]
        name_of[object_id] = obj["name"]
    
    # Phase 2: Filter to valid actor credits and collect distinct movies per person.
    # movies_of: maps person_object_id -> set of distinct valid movie_object_ids, e.g. {501: {10, 20}}.
    # Using a set deduplicates repeated 'actor' rows for the same (person, movie) pair.
    movies_of: Dict[object, Set[object]] = {}
    for credit in credits:
        if normalize_role(credit.get("role")) != "actor":
            # Ignore non-actor roles ('director', 'writer') as well as None or blank roles.
            continue
    
        movie_id = credit["movie_object_id"]
        person_id = credit["person_object_id"]
    
        # Reject dangling IDs (type_of.get returns None) and swapped/wrong-type IDs.
        if type_of.get(movie_id) != "movie" or type_of.get(person_id) != "person":
            continue
    
        if person_id not in movies_of:
            movies_of[person_id] = set()
        movies_of[person_id].add(movie_id)
    
  5. Sort, break ties, and handle tenth-place ties in SQL

    We need movie_count descending and person_object_id ascending. Packing (-movie_count, person_id) tuples lets one ascending ranking.sort() order larger counts first (-3 < -2) while keeping person_id smallest-first (8 < 40):

    # Phase 3: Rank actors by movie_count descending, breaking ties by smaller person_object_id.
    # Negating movie_count lets Python's ascending tuple sort put largest counts first
    # while keeping person_object_id in ascending numeric order.
    ranking = []
    for person_id, movie_set in movies_of.items():
        movie_count = len(movie_set)
        ranking.append((-movie_count, person_id))
    ranking.sort()
    
    # Slice the top 10 (or fewer if fewer than 10 valid actors exist) and format output rows.
    top: List[Dict[str, object]] = []
    for negative_count, person_id in ranking[:10]:
        top.append({
            "person_object_id": person_id,
            "name": name_of[person_id],
            "movie_count": -negative_count,
        })
    

    Variant — keeping everyone tied at 10th place: LIMIT 10 (and ranking[:10]) truncates strictly at 10 rows. If asked to retain all actors tied with the 10th position, filter on RANK() OVER (ORDER BY movie_count DESC) <= 10 (or FETCH FIRST 10 ROWS WITH TIES in standard SQL). Choose RANK(), not DENSE_RANK(): RANK() numbers ties 1, 1, 3, ... so position <= 10 means "fewer than 10 actors strictly beat you," whereas DENSE_RANK() <= 10 keeps the top 10 distinct count values, which can return hundreds of rows!

    WITH actor_counts AS (
        SELECT c.person_object_id,
               p.name,
               COUNT(DISTINCT c.movie_object_id) AS movie_count
        FROM credits AS c
        JOIN objects AS m
          ON m.object_id = c.movie_object_id AND m.object_type = 'movie'
        JOIN objects AS p
          ON p.object_id = c.person_object_id AND p.object_type = 'person'
        WHERE LOWER(TRIM(c.role)) = 'actor'
        GROUP BY c.person_object_id, p.name
    ),
    ranked AS (
        SELECT person_object_id,
               name,
               movie_count,
               RANK() OVER (ORDER BY movie_count DESC) AS position
        FROM actor_counts
    )
    SELECT person_object_id, name, movie_count
    FROM ranked
    WHERE position <= 10
    ORDER BY movie_count DESC, person_object_id ASC;
    
  6. Trace on Example 1 and Example 2

    Tracing top_10_popular_actors across Example 1 (Harbor Light 10, Glass Orbit 20, Night Train 30; Nora 501, Owen 502, Pia 503):

    Credit row             Normalized role  Type check (m, p)   Action on movies_of
    ---------------------  ---------------  ------------------  ---------------------------
    (10, 501, 'actor')     'actor' ok       movie, person ok    movies_of[501] = {10}
    (10, 501, 'director')  skip             -                   unchanged
    (10, 501, 'actor')     'actor' ok       movie, person ok    movies_of[501] = {10} (dup)
    (20, 501, 'actor')     'actor' ok       movie, person ok    movies_of[501] = {10, 20}
    (30, 502, 'actor')     'actor' ok       movie, person ok    movies_of[502] = {30}
    (10, 503, 'director')  skip             -                   503 never enters movies_of
    
    Sorted ranking tuples: [(-2, 501), (-1, 502)]
    Output: Nora (2), Owen (1)
    

    And in Example 2, Tariq (40) gets {1, 2} from 'ACTOR' and ' Actor ', Sana (8) gets {1, 2}, and (-2, 8) < (-2, 40) ranks Sana ahead of Tariq.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def normalize_role(label: object) -> Optional[str]:
        """Trim whitespace and lower-case a role string like ' Actor '; non-strings return None."""
        if not isinstance(label, str):
            return None
        return label.strip().lower()
    
    
    def top_10_popular_actors(objects: List[Dict[str, object]], credits: List[Dict[str, object]]) -> List[Dict[str, object]]:
        # Phase 1: Index objects by ID so we can verify each ID's type and look up person names in O(1) time.
        # Movies and people share the same object_id space, so every join must check object_type.
        # type_of: maps object_id -> 'movie' or 'person', e.g. {10: 'movie', 501: 'person'}.
        # name_of: maps object_id -> display name string, e.g. {10: 'Harbor Light', 501: 'Nora'}.
        type_of: Dict[object, object] = {}
        name_of: Dict[object, object] = {}
        for obj in objects:
            object_id = obj["object_id"]
            type_of[object_id] = obj["object_type"]
            name_of[object_id] = obj["name"]
    
        # Phase 2: Filter to valid actor credits and collect distinct movies per person.
        # movies_of: maps person_object_id -> set of distinct valid movie_object_ids, e.g. {501: {10, 20}}.
        # Using a set deduplicates repeated 'actor' rows for the same (person, movie) pair.
        movies_of: Dict[object, Set[object]] = {}
        for credit in credits:
            if normalize_role(credit.get("role")) != "actor":
                # Ignore non-actor roles ('director', 'writer') as well as None or blank roles.
                continue
    
            movie_id = credit["movie_object_id"]
            person_id = credit["person_object_id"]
    
            # Reject dangling IDs (type_of.get returns None) and swapped/wrong-type IDs.
            if type_of.get(movie_id) != "movie" or type_of.get(person_id) != "person":
                continue
    
            if person_id not in movies_of:
                movies_of[person_id] = set()
            movies_of[person_id].add(movie_id)
    
        # Phase 3: Rank actors by movie_count descending, breaking ties by smaller person_object_id.
        # Negating movie_count lets Python's ascending tuple sort put largest counts first
        # while keeping person_object_id in ascending numeric order.
        ranking = []
        for person_id, movie_set in movies_of.items():
            movie_count = len(movie_set)
            ranking.append((-movie_count, person_id))
        ranking.sort()
    
        # Slice the top 10 (or fewer if fewer than 10 valid actors exist) and format output rows.
        top: List[Dict[str, object]] = []
        for negative_count, person_id in ranking[:10]:
            top.append({
                "person_object_id": person_id,
                "name": name_of[person_id],
                "movie_count": -negative_count,
            })
        return top
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine ranking prolific actors from a crate of end-credit slips where one performer can have multiple slips for the same movie (starring role, voice cameo, plus director) and where movies and performers share one master ID ledger. Rather than tallying raw slips, give each verified performer an envelope for unique film tokens: discard any slip whose normalized role is not 'actor', consult the ledger to verify that the film ID has type 'movie' and the performer ID has type 'person', and place the film token into that performer's envelope only if it is not already inside. Counting tokens per envelope yields each actor's true distinct film total.

Tallying raw credits rows fails because duplicate 'actor' rows and 'director' rows inflate counts—even ranking non-acting directors above working actors. Joining objects on just one column or skipping object_type checks also fails whenever referential integrity (the database guarantee that every foreign key points to an existing record of the intended entity type) is absent, allowing missing IDs or swapped entity types to pollute the leaderboard.

Walk through the traps from Examples 1 and 3: 1. Nora (object_id = 501, 'person') has two 'actor' rows and one 'director' row on film 10 plus one 'actor' row on film 20: the 'director' row is ignored, and her set {10, 20} counts 2 distinct films rather than 4 rows. 2. Credit (movie=404, person=60, role='actor') is dropped because 404 is absent from type_of. 3. Credit (movie=50, person=50, role='actor') where 50 has object_type = 'movie' is dropped because type_of.get(50) is 'movie', not 'person'.

Complexity

  • Time: O(B + C + A log A), where B is len(objects), C is len(credits), and A is the count of qualifying actors (A <= B). Indexing objects into type_of and name_of visits B records in O(B) time, filtering credits performs O(1) dictionary lookups and hash-set insertions across C records (O(C)), and sorting the A (-movie_count, person_id) tuples takes O(A log A) comparisons.
  • Space: O(B + P), where P (P <= C) is the number of distinct valid (person_id, movie_id) pairs stored across movies_of, alongside O(B) entries in type_of and name_of.
  • SQL scaling and indexing: With objects.object_id as the primary key (the unique indexed identifier per row), both inner joins (joins keeping rows only when matching records exist on both sides) execute fast index probes. Normalizing role at ingest time and adding a covering index (an index storing every queried column so the engine avoids reading base-table pages) on (role, person_object_id, movie_object_id) lets the database stream 'actor' credits grouped by actor and film without sorting the full table.

Edge cases

  • Fewer than 10 qualifying actors (including 0): Slicing ranking[:10] (and LIMIT 10 in SQL) returns all available actors, or [] when no valid acting credits exist.
  • Multiple roles or duplicate 'actor' rows on one film: Non-actor roles are skipped up front, and movies_of[person_id] (set) collapses repeated (person_id, movie_id) pairs into 1.
  • Messy or missing roles ('ACTOR', ' Actor ', '', None): normalize_role trims spaces and lower-cases strings while mapping non-strings to None, matching Example 2.
  • Swapped or missing IDs: Requiring type_of.get(movie_id) == 'movie' and type_of.get(person_id) == 'person' rejects missing IDs (None) and wrong-type IDs alike.
  • Ties at or above the cutoff: Integer comparison inside (-movie_count, person_id) orders tied actors numerically (8 before 40 before 100), never by string or input order.
  • Non-acting crew members: People holding only 'director' or 'writer' rows never enter movies_of, so they never appear with movie_count = 0.

Common mistakes

  • Writing COUNT(*) instead of COUNT(DISTINCT movie_object_id). Overcounts performers with multiple acting credits on the same film.
  • Forgetting to filter role before counting distinct films. Credits directors and writers with acting appearances.
  • Joining objects only on person_object_id. Leaves movie_object_id unvalidated, letting nonexistent IDs like 404 or person IDs inflate movie_count.
  • Joining objects once via ON o.object_id IN (c.movie_object_id, c.person_object_id). Checks only one endpoint per joined row instead of verifying both endpoints simultaneously.
  • Checking c.role = 'actor' without trimming and case-folding. Drops valid credits like 'ACTOR' and ' Actor ' in Example 2.
  • Using DENSE_RANK() <= 10 for 10th-place ties. DENSE_RANK() never skips numbers after ties, returning everyone with the top 10 distinct counts rather than top 10 actors plus ties at position 10 (RANK() <= 10).

Alternative approaches

  • Bounded top-10 heap: Using heapq.nsmallest(10, ranking) instead of ranking.sort() extracts the top 10 in O(A log 10) = O(A) time rather than O(A log A).
  • Flat pair set plus counter: Insert valid (person_id, movie_id) tuples into one set and tally person_id frequencies with collections.Counter, mirroring a two-stage SQL CTE (common table expression: a named subquery defined with WITH to structure multi-step SQL).

Follow-up questions

  • Suppose an actor's score is redefined as the sum of viewer interactions across every film they acted in. How would you write the query so duplicate actor rows do not multiply a film's interaction count? Joining raw credits directly to raw interactions causes a multiplicative fan-out: if Nora has two 'actor' rows on Harbor Light and Harbor Light has 500 interactions, a direct join yields 1,000 rows for Nora. Avoid that fan-out with two pre-deduplicated CTEs—actor_movies holding SELECT DISTINCT valid (person_object_id, name, movie_object_id) triples, and film_interactions pre-aggregated to one total per movie_object_id—joined via LEFT JOIN and COALESCE so actors whose films have zero interactions still score 0:

sql WITH actor_movies AS ( SELECT DISTINCT c.person_object_id, p.name, c.movie_object_id FROM credits AS c JOIN objects AS m ON m.object_id = c.movie_object_id AND m.object_type = 'movie' JOIN objects AS p ON p.object_id = c.person_object_id AND p.object_type = 'person' WHERE LOWER(TRIM(c.role)) = 'actor' ), film_interactions AS ( SELECT movie_object_id, COUNT(*) AS interaction_count FROM interactions GROUP BY movie_object_id ) SELECT am.person_object_id, am.name, SUM(COALESCE(fi.interaction_count, 0)) AS score FROM actor_movies AS am LEFT JOIN film_interactions AS fi ON fi.movie_object_id = am.movie_object_id GROUP BY am.person_object_id, am.name ORDER BY score DESC, am.person_object_id ASC LIMIT 10;

  • If the credit log contains billions of records and clients fetch this leaderboard constantly, how would you materialize and incrementally update the counts? Re-aggregating billions of credit rows on every request is prohibitive, so maintain two compact tables: actor_film_links(person_object_id, movie_object_id, credit_row_count) with a unique key on (person_object_id, movie_object_id), and actor_film_totals(person_object_id, name, movie_count) indexed on (movie_count DESC, person_object_id ASC). When a validated acting credit arrives, increment credit_row_count in actor_film_links and increment movie_count in actor_film_totals only when credit_row_count rises from 0 to 1 (and on deletes, decrement movie_count only when credit_row_count falls from 1 to 0). Leaderboard reads then scan just 10 index entries—or hit a short-TTL cache—while a periodic batch job verifies consistency.
  • How could a single SQL query return separate top-10 leaderboards for both actors and directors? Filter to LOWER(TRIM(c.role)) IN ('actor', 'director'), group by the normalized role alongside (person_object_id, name) so people who both act and direct get an independent count per role, and rank within each role using a window function (a SQL calculation evaluated across a partition of rows without collapsing them) with PARTITION BY normalized_role:

sql WITH role_counts AS ( SELECT LOWER(TRIM(c.role)) AS normalized_role, c.person_object_id, p.name, COUNT(DISTINCT c.movie_object_id) AS movie_count FROM credits AS c JOIN objects AS m ON m.object_id = c.movie_object_id AND m.object_type = 'movie' JOIN objects AS p ON p.object_id = c.person_object_id AND p.object_type = 'person' WHERE LOWER(TRIM(c.role)) IN ('actor', 'director') GROUP BY LOWER(TRIM(c.role)), c.person_object_id, p.name ), ranked AS ( SELECT normalized_role, person_object_id, name, movie_count, ROW_NUMBER() OVER ( PARTITION BY normalized_role ORDER BY movie_count DESC, person_object_id ASC) AS rk FROM role_counts ) SELECT normalized_role AS role, rk AS position, person_object_id, name, movie_count FROM ranked WHERE rk <= 10 ORDER BY role ASC, position ASC;

Follow-up questions

Similar questions

More Scribd interview questions

All 5 Scribd questions →