Describe a complex SQL query you developed to optimize data retrieval.
Use the provided customer, order, and order-item tables to produce a customer-level retrieval result that includes active customers and completed-order metrics.
Output
- One row per active customer, including customers without completed orders.
- Return
customer_id, customer_name, completed_orders, total_spend, latest_order_date, and customer_segment.
- Sort by
total_spend descending, then customer_id ascending.
Output details
- Treat customers with
is_active = TRUE as active.
- Count only orders whose status is
completed, counting each completed order once per customer.
- Calculate each order's spend as the sum of
quantity * unit_price across its items.
- Return
total_spend with exactly two decimal places, using 0.00 when the calculated total is null or absent.
- Return
latest_order_date as NULL when a customer has no completed orders.
- Classify customers with no completed orders as
No orders; otherwise use High for spend at least 500, and Standard below 500.