|
| 1 | +WITH Ranked_Products AS ( |
| 2 | + SELECT |
| 3 | + p.product_id, |
| 4 | + p.product_name, |
| 5 | + p.price, |
| 6 | + RANK() OVER (ORDER BY p.price DESC) AS price_rank |
| 7 | + FROM |
| 8 | + products p |
| 9 | +), |
| 10 | +Top_Customers AS ( |
| 11 | + SELECT |
| 12 | + c.customer_id, |
| 13 | + c.first_name, |
| 14 | + c.last_name, |
| 15 | + SUM(o.total_amount) AS total_spent, |
| 16 | + COUNT(o.order_id) AS order_count, |
| 17 | + RANK() OVER (ORDER BY SUM(o.total_amount) DESC) AS spending_rank |
| 18 | + FROM |
| 19 | + customers c |
| 20 | + JOIN |
| 21 | + orders o ON c.customer_id = o.customer_id |
| 22 | + GROUP BY |
| 23 | + c.customer_id, c.first_name, c.last_name |
| 24 | +) |
| 25 | +SELECT |
| 26 | + tc.customer_id, |
| 27 | + CONCAT(tc.first_name, ' ', tc.last_name) AS customer_name, |
| 28 | + tc.total_spent, |
| 29 | + tc.order_count, |
| 30 | + tc.spending_rank, |
| 31 | + rp.product_name, |
| 32 | + rp.price, |
| 33 | + rp.price_rank |
| 34 | +FROM |
| 35 | + Top_Customers tc |
| 36 | +JOIN |
| 37 | + order_details od ON tc.customer_id = od.customer_id |
| 38 | +JOIN |
| 39 | + Ranked_Products rp ON od.product_id = rp.product_id |
| 40 | +WHERE |
| 41 | + rp.price_rank <= 5 AND tc.spending_rank <= 10 |
| 42 | +ORDER BY |
| 43 | + tc.spending_rank, rp.price_rank; |
0 commit comments