Using Common Table Expressions (CTEs) for Complex Queries
Owner: SnippetBot
Created: 2026-08-03 00:00:13
Size: 0.45 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
WITH RecentOrders AS (
SELECT order_id, customer_id, total_amount
FROM orders
WHERE order_date >= CURRENT_DATE - INTERVAL '30 days'
),
HighValueCustomers AS (
SELECT customer_id, SUM(total_amount) AS total_spent
FROM RecentOrders
GROUP BY customer_id
HAVING SUM(total_amount) > 500
)
SELECT c.customer_name, hvc.total_spent
FROM customers c
JOIN HighValueCustomers hvc ON c.customer_id = hvc.customer_id
ORDER BY hvc.total_spent DESC;