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
61 changes: 61 additions & 0 deletions Market Analysis II.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
-- Solution for Mock SQL 3 question : Market Analysis II
-- Method 1
WITH cnt AS (
SELECT seller_id,
COUNT(*) cnt
FROM orders
GROUP BY seller_id
),
main AS (
SELECT user_id AS seller_id,
2nd_item_fav_brand,
rwn
FROM (
SELECT u.user_id,
-- o.order_date,
-- i.item_brand,
-- u.favorite_brand,
CASE
WHEN i.item_brand = u.favorite_brand AND c.cnt > 1 THEN 'yes'
ELSE 'no'
END AS 2nd_item_fav_brand,
ROW_NUMBER() OVER(PARTITION BY u.user_id ORDER BY o.order_date) AS rwn
FROM users u
LEFT JOIN orders o
ON o.seller_id = u.user_id
LEFT JOIN items i
ON o.item_id = i.item_id
LEFT JOIN cnt c
ON u.user_id = c.seller_id
ORDER BY u.user_id, o.order_date
) a
WHERE rwn IN (1,2)
)
SELECT seller_id,
2nd_item_fav_brand
FROM main
WHERE (seller_id, rwn) IN (SELECT seller_id, MAX(rwn) FROM main GROUP BY seller_id);

-- Method 2
WITH cte AS (
SELECT order_date,
item_brand,
seller_id,
RANK() OVER(PARTITION BY o.seller_id ORDER BY o.order_date) AS 'rnk'
FROM orders o
JOIN items i
ON o.item_id = i.item_id
),
cte2 AS (
SELECT *
FROM cte
WHERE rnk = 2
)
SELECT user_id AS 'seller_id',
CASE
WHEN rnk = 2 AND item_brand = favorite_brand THEN 'yes'
ELSE 'no'
END AS '2nd_item_fav_brand'
FROM users
LEFT JOIN cte2
ON cte2.seller_id = users.user_id;
28 changes: 28 additions & 0 deletions Tournament Winners.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
-- Soution for Mock SQL 3 question: Tournament Winners
WITH cte AS (
SELECT player_id,
SUM(score) AS score
FROM (
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
) a
GROUP BY player_id
)
SELECT group_id,
player_id
FROM (
SELECT p.group_id,
c.player_id,
c.score,
ROW_NUMBER() OVER(PARTITION BY p.group_id ORDER BY c.score DESC, c.player_id) rwn
-- order by score desc first so that we consider the max scored player, and then sorting by player_id ascending so that we capture the lowest player_id in case of a tie.
FROM players p
JOIN cte c
ON p.player_id = c.player_id
) a
WHERE rwn = 1;