Optimize a slow-running SQL query containing multiple subqueries and complex joins on a distributed data warehouse like Snowflake or Redshift.
Using the supplied PostgreSQL schema, write an optimized query that calculates the requested monthly viewing metrics without changing the result. Restrict analysis to the latest and immediately preceding calendar month represented in the viewing data.
Output
- One row per plan and genre in the top two genres by current-month minutes.
- Columns:
plan_name, genre, current_minutes, prior_minutes, percent_change, and genre_rank.
- Include only play events covered by an active subscription, order by
plan_name, genre_rank, and genre.