You're building a comprehensive customer analytics system for an e-commerce platform! Given two database tables containing transaction history and product information, you need to analyze customer purchasing behavior and calculate key metrics that drive business decisions.
Your task is to generate a detailed customer profile for each customer that includes:
- Financial Metrics: Total spending, average transaction amount
- Engagement Metrics: Number of transactions, unique product categories explored
- Behavioral Insights: Most frequently purchased category (with recency tiebreaker)
- Loyalty Score: A custom formula combining transaction frequency and spending:
(transactions ร 10) + (total_amount รท 100)
The challenge lies in handling tied categories - when a customer purchases equally from multiple categories, you must select the category from their most recent transaction. Results should be ordered by loyalty score (descending), then by customer ID (ascending).
This problem mimics real-world customer segmentation and loyalty program analysis used by companies like Amazon, Netflix, and Spotify!
Input & Output
Visualization
Time & Space Complexity
Single scan of joined tables (n) plus sorting for window functions and final ORDER BY
Where k is the number of unique customers for intermediate window function results
Constraints
- 1 โค transaction_id โค 106
- 1 โค customer_id โค 104
- 1 โค product_id โค 103
- 0.01 โค amount โค 104
- transaction_date is in 'YYYY-MM-DD' format
- Each customer will have at least 1 transaction
- Product categories are non-empty varchar strings
- All amounts should be rounded to 2 decimal places