SELECT   
    cast1.cast_id         AS cast_member_id1,
    cast2.cast_id         AS cast_member_id2,
    Count(cast1.movie_id) AS cocasted,
    AVG(movie.score)      AS avg_score
FROM     movie_cast cast1

JOIN     movie_cast cast2
    ON       cast1.movie_id = cast2.movie_id

JOIN     movies movie
    ON       cast1.movie_id = movie.id

AND      cast1.cast_id < cast2.cast_id

JOIN    movies movie1
    ON cast1.movie_id = movie1.id

GROUP BY cast1.cast_id, cast2.cast_id
HAVING cocasted >= 3 AND avg_score >= 40
ORDER BY cocasted DESC;