Common Table Expression Chained
Chain multiple CTEs for readable complex query decomposition in SQL reports.
Code
WITH active_users AS (
SELECT id, name FROM users WHERE status = 'active'
),
user_orders AS (
SELECT u.id, u.name, COUNT(o.id) AS order_count
FROM active_users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id, u.name
),
ranked AS (
SELECT *, RANK() OVER (ORDER BY order_count DESC) AS rnk
FROM user_orders
)
SELECT id, name, order_count
FROM ranked
WHERE rnk <= 10
ORDER BY rnk;Report a problem with this exampleOpens a pre-filled issue on GitHub.