File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed
interview-query-solutions/Hard Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change 1+ -- Solution 1: using recursive cte
2+
3+ WITH RECURSIVE CTE as (
4+ SELECT int_numbers, 1 as flag
5+ FROM tbl_numbers
6+ UNION ALL
7+ SELECT int_numbers, flag+ 1
8+ FROM CTE
9+ WHERE flag < int_numbers
10+ )
11+ SELECT int_numbers as seq_numbers
12+ FROM CTE
13+ ORDER BY 1
14+
15+
16+
17+ -- Solution 2: very easy in PostgreSQL
18+ -- using CROSS join & generate_series
19+
20+ SELECT int_numbers AS seq_numbers
21+ FROM tbl_numbers CROSS JOIN generate_series(1 , int_numbers)
22+
23+
24+ -- NOTE: read the question and immendiately thought of recursive cte.
Original file line number Diff line number Diff line change 1+ WITH already_friends AS (
2+ SELECT friend_id
3+ FROM friends
4+ WHERE user_id= 3
5+ ),
6+ blocked AS (
7+ SELECT blocked_id
8+ FROM blocks
9+ WHERE user_id= 3
10+ ),
11+ liked AS (
12+ SELECT page_id
13+ FROM likes
14+ WHERE user_id= 3
15+ ),
16+ friend_points AS (
17+ SELECT user_id, SUM (3 ) AS points
18+ FROM friends
19+ WHERE friend_id IN (SELECT friend_id FROM already_friends)
20+ GROUP BY 1
21+ ),
22+ like_points AS (
23+ SELECT user_id, SUM (2 ) AS points
24+ FROM likes
25+ WHERE page_id IN (SELECT page_id FROM liked)
26+ GROUP BY 1
27+ )
28+ SELECT u .name AS potential_friend_name, SUM (points) AS friendship_points
29+ FROM (
30+ SELECT user_id, points
31+ FROM friend_points
32+ UNION
33+ SELECT user_id, points
34+ FROM like_points
35+ ) f LEFT JOIN users u ON f .user_id = u .user_id
36+ WHERE u .user_id NOT IN (SELECT friend_id FROM already_friends) AND
37+ u .user_id NOT IN (SELECT blocked_id FROM blocked) AND
38+ u .user_id != 3
39+ GROUP BY 1
40+ ORDER BY 2 , 1
41+
42+
You can’t perform that action at this time.
0 commit comments