Problems / Basic CTE Filter / Editorial
WITH active_subs AS (SELECT * FROM subscriptions WHERE status = 'active')
SELECT plan, COUNT(*) AS active_count FROM active_subs GROUP BY plan
plan
Plans whose subscriptions are all cancelled or paused never reach the GROUP BY, so they simply don't appear — exactly what the problem asks for.
In PySpark the same two-step shape falls out naturally: bind the filtered DataFrame to a variable (active_subs = subscriptions.filter(...)), then aggregate it.
active_subs = subscriptions.filter(...)
A CTE doesn't change what the query computes — SELECT plan, COUNT(*) FROM subscriptions WHERE status = 'active' GROUP BY plan is equivalent. Its value is readability and reuse: each pipeline stage gets a name, and later problems chain several CTEs where inlining everything would be unreadable.
SELECT plan, COUNT(*) FROM subscriptions WHERE status = 'active' GROUP BY plan
Solve Basic CTE Filter yourself →