Brightlane's fulfillment analysis pipeline materializes high-volume statuses — those with more than 10 orders on record — into a temp table for downstream operations reporting.
Write a query to return the status and order count for each high-volume status.
Assumptions:
- The
orderstable has one row per order with astatus. - A status's order count is the number of orders carrying that
status. - Only statuses with an order count greater than
10should appear.
Output:
- One row per qualifying status, with columns
statusandorder_count.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
WITH
status_counts AS (
SELECT
status,
COUNT(*) AS order_count
FROM
orders
GROUP BY
status
),
high_volume AS (
SELECT
status,
order_count
FROM
status_counts
WHERE
order_count > 10
)
SELECT
status,
order_count
FROM
high_volume The shape
A two-stage chained CTE: the first stage groups orders by status and counts them, the second stage filters that result to statuses whose count exceeds 10. Two separate WITH blocks make each stage independently named, which is the readability win when a pipeline plans to materialize each intermediate result on its way to the final temp table.
Clause by clause
WITH status_counts AS (SELECT status, COUNT(*) AS order_count FROM orders GROUP BY status)is the first CTE. It groups every order bystatusand counts the orders in each group, producing one row per distinct status.high_volume AS (SELECT status, order_count FROM status_counts WHERE order_count > 10)is the second CTE, which reads the first one and keeps only the rows whose count exceeds 10. The filter compares againstorder_count, which the first CTE made available as a real column.SELECT status, order_count FROM high_volumereads the filtered result and returns both columns. On this data the four high-volume statuses survive:deliveredat 161,shippedat 17,cancelledandpendingat 11 each.
Why chain two CTEs and not collapse into one
A single CTE wrapping a derived-table filter would compute the same result. The chained form pays off when the pipeline plans to materialize both stages: status_counts is itself a reusable intermediate, and other downstream queries in the same session might want the full count list before the high-volume filter is applied. Naming each stage separately means each one can become a temp table of its own. Collapsing the two into a single expression hides that boundary.
You practiced a two-stage aggregation: count records per category, then keep only categories whose count exceeds a threshold — a compact restricted-aggregate shape ready to populate a temp table.