1WITH ranked_products AS (
2 SELECT
3 c.country,
4 cat.category_name,
5 p.product_name,
6 SUM(od.quantity * od.unit_price) AS total_sales,
7 ROUND(
8 100.0 * SUM(od.quantity * od.unit_price)
9 / SUM(SUM(od.quantity * od.unit_price)) OVER (PARTITION BY c.country, cat.category_id),
10 2
11 ) AS sales_percentage,
12 RANK() OVER (
13 PARTITION BY c.country, cat.category_id
14 ORDER BY SUM(od.quantity * od.unit_price) DESC
15 ) AS sales_rank
16 FROM orders o
17 JOIN order_details od ON o.order_id = od.order_id
18 JOIN products p ON od.product_id = p.product_id
19 JOIN categories cat ON p.category_id = cat.category_id
20 JOIN customers c ON o.customer_id = c.customer_id
21 WHERE o.order_date BETWEEN '2023-01-01' AND '2023-12-31'
22 AND c.country IN ('USA', 'UK', 'Germany')
23 GROUP BY c.country, cat.category_id, cat.category_name, p.product_name
24),
25category_stats AS (
26 SELECT
27 country,
28 category_name,
29 SUM(total_sales) AS category_total,
30 COUNT(DISTINCT CASE WHEN sales_rank <= 3 THEN product_name END) AS top_products_count
31 FROM ranked_products
32 GROUP BY country, category_name
33 HAVING SUM(total_sales) > 50000
34)
35SELECT
36 rp.country,
37 rp.category_name,
38 rp.product_name,
39 rp.total_sales,
40 rp.sales_percentage,
41 cs.category_total,
42 CASE
43 WHEN rp.sales_rank <= 3 THEN 'Top 3'
44 ELSE 'Other'
45 END AS performance_flag,
46 LAG(rp.total_sales, 1) OVER (
47 PARTITION BY rp.country, rp.category_name
48 ORDER BY rp.sales_rank
49 ) AS prev_product_sales
50FROM ranked_products rp
51JOIN category_stats cs
52 ON rp.country = cs.country
53 AND rp.category_name = cs.category_name
54WHERE rp.sales_rank <= 5
55ORDER BY
56 rp.country,
57 cs.category_total DESC,
58 rp.sales_rank;