Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions 01-TournamentWinners.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
-- Problem 1 - Tournament Winners (https://leetcode.com/problems/tournament-winners/description/)
-- Step 1 - Grouping Players From first_player and second_player columns in Matches
WITH groupedplayers AS(
SELECT first_player AS 'player_id', first_score AS 'score'
FROM Matches
UNION ALL
SELECT second_player AS 'player_id', second_score AS 'score'
FROM Matches
),
-- Step 2 - Computing total scores of each player
sumscores AS(
SELECT player_id, SUM(score) AS 'total_score'
FROM groupedplayers
GROUP BY player_id
),
-- Step 3 - Ranking Players Based on Score Using DENSE_RANK()
rankedplayers AS(
SELECT p.group_id AS 'group_id', s.player_id AS 'player_id', DENSE_RANK() OVER(PARTITION BY p.group_id ORDER BY s.total_score DESC, s.player_id) AS 'rnk'
FROM Players p
INNER JOIN sumscores s
ON p.player_id = s.player_id
GROUP BY p.player_id, p.group_id
)
-- Step 4 - Selecting the top player in each group based on score
SELECT r.group_id, r.player_id
FROM rankedplayers r
WHERE rnk = 1;
25 changes: 25 additions & 0 deletions 02-MarketAnalysis-II.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
-- Problem 2 - Market Analysis II - (https://leetcode.com/problems/market-analysis-ii/)
-- Step 1 - Ordering Items
WITH ordereditems AS(
SELECT o.order_date AS 'order_date', o.seller_id AS 'seller_id', i.item_brand AS 'item_brand'
FROM Orders o
INNER JOIN Items i
ON o.item_id = i.item_id
),
-- Step 2 - Favorite Brands of Each User Found
favbrand AS (
SELECT u.user_id AS 'user_id', u.favorite_brand AS 'fav_brand', o.item_brand AS 'item_brand', ROW_NUMBER() OVER(PARTITION BY u.user_id ORDER BY o.order_date) AS 'rnk'
FROM Users u
INNER JOIN ordereditems o
ON u.user_id = o.seller_id
)
-- Step 3 - Finding Second Favorite Item of Each User
SELECT u.user_id AS 'seller_id',
CASE
WHEN f.item_brand = u.favorite_brand THEN 'yes'
ELSE 'no'
END AS '2nd_item_fav_brand'
FROM Users u
LEFT JOIN favbrand f
ON u.user_id = f.user_id
AND f.rnk = 2;