Create a readable query pipeline with `WITH`.
Section: subqueries and ctes
Use a CTE to isolate recent orders
sql
sql
WITH recent_orders AS (
SELECT id, user_id, total_amount, created_at
FROM orders
WHERE created_at >= NOW() - INTERVAL 30 DAY
)
SELECT user_id, COUNT(*) AS recent_order_count, SUM(total_amount) AS revenue
FROM recent_orders
GROUP BY user_id;Explanation
CTEs help break complex logic into named steps.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing subqueries and ctes
Left join to keep unmatched parent rows
Return all rows from the left table and matching rows from the right table.