SQL
Lab
Meta Meta Interview Question 03

Feed
Ranking

Rank posts in a user's feed based on total engagement.

Table Schema

Inspect
Table

interactive
ColumnType
post_idinteger
user_idinteger
ColumnType
post_idinteger
reaction_typevarchar

Sample Data

Input
Output

Sample Input: posts
post_iduser_id
1101
2102
3103
Sample Input: reactions
post_idreaction_type
1like
1comment
2like
2like
3like
Expected Output
post_idrank
11
22
33

SQL Editor

Run
Query

postgresql
Waiting for query

post_idrank
11
22
33

Hints

Unlock
Clues

Hint 01: Identify the grouping level required by the output.
Hint 02: Aggregate with COUNT, SUM, AVG, or a window function as needed.
Hint 03: Filter after aggregation with HAVING or after ranking with an outer query.

Solution

Locked
Answer

Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.

WITH engagement AS (
  SELECT p.post_id, COUNT(r.reaction_type) AS total_engagement
  FROM posts p
  LEFT JOIN reactions r ON p.post_id = r.post_id
  GROUP BY p.post_id
)
SELECT post_id, RANK() OVER (ORDER BY total_engagement DESC) AS rank
FROM engagement;

Explanation

Step By
Step

01

Read the expected output columns to determine the final grain.

02

Aggregate or rank the input rows to calculate the requested metric.

03

Filter, sort, and alias the final columns to match the output.

Related Questions

Keep
Solving