Problems / Multi-CTE Pipeline / Editorial
completed_orders
WHERE status = 'completed'
customer_revenue
FROM completed_orders
customer_id
SUM(amount) AS total_revenue
customers
customer_name
total_revenue > 500
total_revenue DESC, customer_id
The PySpark translation is one intermediate DataFrame per CTE: completed_orders = orders.filter(...), then customer_revenue = completed_orders.groupBy(...).agg(...), then filter + join + select.
completed_orders = orders.filter(...)
customer_revenue = completed_orders.groupBy(...).agg(...)
Stage order is the whole game. Filtering by status must happen before the SUM — a customer with $450 completed plus $200 cancelled has $650 total but only $450 of real revenue, and must not appear. And the revenue threshold must be applied after the SUM (on the aggregate, not on individual order amounts): a customer can cross $500 through many small orders none of which exceeds $500 alone. CTEs make that ordering explicit and readable; an inner join to customers suffices since customers with no completed revenue can't clear the threshold anyway.
Solve Multi-CTE Pipeline yourself →