Skip to content

Commit ecf673e

Browse files
Create 6_ranking_analysis.sql
1 parent 8d6241e commit ecf673e

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

scripts/6_ranking_analysis.sql

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
===============================================================================
3+
Ranking Analysis
4+
===============================================================================
5+
Purpose:
6+
- To rank items (e.g., products, customers) based on performance or other metrics.
7+
- To identify top performers or laggards.
8+
9+
SQL Functions Used:
10+
- Window Ranking Functions: RANK(), DENSE_RANK(), ROW_NUMBER(), TOP
11+
- Clauses: GROUP BY, ORDER BY
12+
===============================================================================
13+
*/
14+
15+
-- Which 5 products Generating the Highest Revenue?
16+
-- Simple Ranking
17+
SELECT TOP 5
18+
p.product_name,
19+
SUM(f.sales_amount) AS total_revenue
20+
FROM gold.fact_sales f
21+
LEFT JOIN gold.dim_products p
22+
ON p.product_key = f.product_key
23+
GROUP BY p.product_name
24+
ORDER BY total_revenue DESC;
25+
26+
-- Complex but Flexibly Ranking Using Window Functions
27+
SELECT *
28+
FROM (
29+
SELECT
30+
p.product_name,
31+
SUM(f.sales_amount) AS total_revenue,
32+
RANK() OVER (ORDER BY SUM(f.sales_amount) DESC) AS rank_products
33+
FROM gold.fact_sales f
34+
LEFT JOIN gold.dim_products p
35+
ON p.product_key = f.product_key
36+
GROUP BY p.product_name
37+
) AS ranked_products
38+
WHERE rank_products <= 5;
39+
40+
-- What are the 5 worst-performing products in terms of sales?
41+
SELECT TOP 5
42+
p.product_name,
43+
SUM(f.sales_amount) AS total_revenue
44+
FROM gold.fact_sales f
45+
LEFT JOIN gold.dim_products p
46+
ON p.product_key = f.product_key
47+
GROUP BY p.product_name
48+
ORDER BY total_revenue;
49+
50+
-- Find the top 10 customers who have generated the highest revenue
51+
SELECT TOP 10
52+
c.customer_key,
53+
c.first_name,
54+
c.last_name,
55+
SUM(f.sales_amount) AS total_revenue
56+
FROM gold.fact_sales f
57+
LEFT JOIN gold.dim_customers c
58+
ON c.customer_key = f.customer_key
59+
GROUP BY
60+
c.customer_key,
61+
c.first_name,
62+
c.last_name
63+
ORDER BY total_revenue DESC;
64+
65+
-- The 3 customers with the fewest orders placed
66+
SELECT TOP 3
67+
c.customer_key,
68+
c.first_name,
69+
c.last_name,
70+
COUNT(DISTINCT order_number) AS total_orders
71+
FROM gold.fact_sales f
72+
LEFT JOIN gold.dim_customers c
73+
ON c.customer_key = f.customer_key
74+
GROUP BY
75+
c.customer_key,
76+
c.first_name,
77+
c.last_name
78+
ORDER BY total_orders ;

0 commit comments

Comments
 (0)