-- QUERY 1: Customer Segmentation Analysis
WITH customer_metrics AS (
SELECT
c.CustomerID,
c.CompanyName,
c.Country,
c.City,
COUNT(DISTINCT o.OrderID) as total_orders,
ROUND(SUM(od.UnitPrice * od.Quantity * (1 - od.Discount)), 2) as lifetime_revenue,
ROUND(AVG(od.UnitPrice * od.Quantity * (1 - od.Discount)), 2) as avg_order_value,
MIN(o.OrderDate) as first_order_date,
MAX(o.OrderDate) as last_order_date,
ROUND(JULIANDAY(MAX(o.OrderDate)) - JULIANDAY(MIN(o.OrderDate))) as customer_lifetime_days,
SUM(od.Quantity) as total_units_purchased,
ROUND(AVG(od.Discount) * 100, 2) as avg_discount_percent
FROM Customers c
JOIN Orders o ON c.CustomerID = o.CustomerID
JOIN OrderDetails od ON o.OrderID = od.OrderID
GROUP BY c.CustomerID, c.CompanyName, c.Country, c.City
),
ranked_customers AS (
SELECT *,
ROW_NUMBER() OVER (ORDER BY lifetime_revenue DESC) as revenue_rank,
COUNT(*) OVER () as total_customers
FROM customer_metrics
),
customer_segments AS (
SELECT *,
CASE
WHEN revenue_rank <= CAST(total_customers * 0.15 AS INTEGER) THEN 'VIP Champions'
WHEN revenue_rank <= CAST(total_customers * 0.35 AS INTEGER) THEN 'High Value'
WHEN revenue_rank <= CAST(total_customers * 0.65 AS INTEGER) THEN 'Growing'
ELSE 'At Risk'
END as customer_segment
FROM ranked_customers
)
SELECT
customer_segment,
COUNT(*) as customer_count,
ROUND(AVG(lifetime_revenue), 2) as avg_lifetime_revenue,
ROUND(AVG(avg_order_value), 2) as avg_order_value,
ROUND(AVG(total_orders), 1) as avg_orders_per_customer,
ROUND(AVG(customer_lifetime_days)) as avg_customer_lifetime_days,
ROUND(SUM(lifetime_revenue), 2) as segment_total_revenue,
ROUND(SUM(lifetime_revenue) * 100.0 / (SELECT SUM(lifetime_revenue) FROM customer_segments), 2) as revenue_percentage
FROM customer_segments
GROUP BY customer_segment
ORDER BY avg_lifetime_revenue DESC;