A multinational retailer wants to analyze product profitability across regions by calculating profit margins, ranking top-performing products, and identifying trends using window functions. How would you structure an SQL query with CTEs and window functions to derive these insights from a sales transactions table?
Interview
How to structure your answer
Use the Profitability Tree framework to decompose profitability into revenue, costs, and margins. Structure the SQL with CTEs for data aggregation, then apply window functions for ranking and trend analysis. Ensure MECE (Mutually Exclusive, Collectively Exhaustive) principles to avoid overlapping calculations across regions and products.
Sample answer
To analyze product profitability, first create a CTE to calculate profit per transaction by joining sales data with product and region tables. Aggregate revenue, cost, and profit at the product-region level. Compute profit margin as (profit / revenue) * 100. Use a window function like RANK() OVER (PARTITION BY region ORDER BY profit_margin DESC) to identify top-performing products. For trends, apply ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY transaction_date) to track performance over time. Finally, join results to visualize rankings and trends. This approach ensures clarity and scalability for regional comparisons.
Key points to mention
- • CTE structure for data organization
- • PARTITION BY region and product_id in window functions
- • Profit margin calculation in initial CTE
Common mistakes to avoid
- ✗ Forgetting to partition by region in window functions
- ✗ Not using CTEs for intermediate calculations
- ✗ Incorrect profit margin formula