WITH ranked_products AS ( SELECT c.country, cat.category_name, p.product_name, SUM(od.quantity * od.unit_price) AS total_sales, ROUND( 100.0 * SUM(od.quantity * od.unit_price) / SUM(SUM(od.quantity * od.unit_price)) OVER (PARTITIONBY c.country, cat.category_id), 2 ) AS sales_percentage, RANK() OVER ( PARTITIONBY c.country, cat.category_id ORDERBY SUM(od.quantity * od.unit_price) DESC ) AS sales_rank FROM orders o JOIN order_details od ON o.order_id = od.order_id JOIN products p ON od.product_id = p.product_id JOIN categories cat ON p.category_id = cat.category_id JOIN customers c ON o.customer_id = c.customer_id WHERE o.order_date BETWEEN'2023-01-01'AND'2023-12-31' AND c.country IN ('USA', 'UK', 'Germany') GROUPBY c.country, cat.category_id, cat.category_name, p.product_name ), category_stats AS ( SELECT country, category_name, SUM(total_sales) AS category_total, COUNT(DISTINCTCASEWHEN sales_rank <= 3THEN product_name END) AS top_products_count FROM ranked_products GROUPBY country, category_name HAVING SUM(total_sales) > 50000 ) SELECT rp.country, rp.category_name, rp.product_name, rp.total_sales, rp.sales_percentage, cs.category_total, CASE WHEN rp.sales_rank <= 3THEN'Top 3' ELSE'Other' ENDAS performance_flag, LAG(rp.total_sales, 1) OVER ( PARTITIONBY rp.country, rp.category_name ORDERBY rp.sales_rank ) AS prev_product_sales FROM ranked_products rp JOIN category_stats cs ON rp.country = cs.country AND rp.category_name = cs.category_name WHERE rp.sales_rank <= 5 ORDERBY rp.country, cs.category_total DESC, rp.sales_rank;
-- 添加索引以提高查询性能(可选) CREATEINDEX idx_orders_customer_id ON orders(customer_id); CREATEINDEX idx_order_details_order_id ON order_details(order_id); CREATEINDEX idx_order_details_product_id ON order_details(product_id); CREATEINDEX idx_products_category_id ON products(category_id);