Skip to content

Commit ef23c72

Browse files
authored
Create premier-league-table-ranking-ii.sql
1 parent 868820c commit ef23c72

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Time: O(nlogn)
2+
# Space: O(n)
3+
4+
# window function
5+
WITH teams_points_cte AS (
6+
SELECT team_id,
7+
team_name,
8+
wins * 3 + draws * 1 + losses * 0 AS points
9+
FROM TeamStats
10+
), teams_ranks_cte AS (
11+
SELECT team_id,
12+
team_name,
13+
points,
14+
RANK() OVER (ORDER BY points DESC) AS position
15+
FROM teams_points_cte
16+
), team_count_cte as (
17+
SELECT COUNT(*) as num_teams
18+
FROM TeamStats
19+
)
20+
21+
SELECT team_name,
22+
points,
23+
position,
24+
CASE WHEN position <= CEIL(num_teams * 0.33) THEN "Tier 1"
25+
WHEN position <= CEIL(num_teams * 0.66) THEN "Tier 2"
26+
ELSE "Tier 3"
27+
END AS tier
28+
FROM teams_ranks_cte, team_count_cte
29+
ORDER BY 2 DESC, 1;

0 commit comments

Comments
 (0)