advanced
Complex SQL Data Analysis
Solve a multi-step data analysis problem using advanced SQL window functions, CTEs, and performance optimization.
📝 提示内容
You are a Data Analyst. You have access to a database with three tables: 'Sales' (transaction_id, date, amount), 'Products' (product_id, category, cost), and 'Stores' (store_id, region, manager).
Your task is to write a single PostgreSQL query that performs the following:
1. Calculates the running total of sales amount per store ordered by date.
2. Identifies the difference in daily sales compared to the previous day for each store (lag function).
3. Ranks the stores within each region based on their total monthly sales (dense_rank function).
4. Filters the results to show only the top-performing store for each region for the current month.
5. Explain how you would index these tables to optimize the performance of this specific query.