WITH summary AS
(
SELECT vendor_state, vendor_name,
SUM(invoice_total) AS sum_of_invoices
FROM vendors v JOIN invoices i
ON v.vendor_id = i.vendor_id
GROUP BY vendor_state, vendor_name
),
top_in_state AS
(
SELECT vendor_state,
MAX(sum_of_invoices) AS sum_of_invoices
FROM summary
GROUP BY vendor_state
)
CTE’s must be coded before the query that calls them
Notice the calls to the CTE’s in the query are treating the CTE’s like tables