简体   繁体   中英

To find actors who were never unemployed for more than 3 years in a stretch

I'm suppose to find the actors that were never unemployed for more than 3 years at a stretch. (Assume that the actors remain unemployed between two consecutive movies).

The M_cast represents the actors and person table has the name of the actor and the movie table has the year column.

SQL code:

SELECT a.Name, c.year
FROM Person a
Inner Join M_cast b
ON a.PID = b.PID
Inner Join Movie c
ON c.MID = b.MID

This would give us all the actor name and the various years they worked , however, I'm not sure how to check if the an actor worked for 3 years in a row or not. Would appreciate your insights on this. If a similar question was asked anywhere else, please point me in the right direction.

So you've got the Actors, Movies (Work), and the Year for each of the Movies. My approach to this would be to use the LEAD() function to add a new column next_year .

A bit of background on the function:

LEAD() is a window function that provides access to a row at a specified physical offset which follows the current row.

For example, by using the LEAD() function, from the current row, you can access data of the next row, or the row after the next row, and so on.

The LEAD() function can be very useful for comparing the value of the current row with the value of the following row.

The following shows the syntax of the LEAD() function:

LEAD(return_value ,offset [,default])
OVER (
    [PARTITION BY partition_expression, ... ]
    ORDER BY sort_expression [ASC | DESC], ...
)

Example use:

SELECT *
, LEAD(year, 1, 0) OVER (PARTITION BY Name ORDER BY year ASC) AS next_year
FROM (yourJoinedTable)

Using (next_year - year) AS gap you can create a column of gaps between movies (years unemployed). Finally, find the MAX(gap) for each actor and filter those actors out which have a MAX(gap) of ≤ 3. This should leave you with only actors that have no more than 3 years between movies.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM