Table Schema
Inspect
Table
| Column | Type |
|---|---|
| post_id | integer |
| user_id | integer |
| Column | Type |
|---|---|
| post_id | integer |
| reaction_type | varchar |
Rank posts in a user's feed based on total engagement.
Table Schema
| Column | Type |
|---|---|
| post_id | integer |
| user_id | integer |
| Column | Type |
|---|---|
| post_id | integer |
| reaction_type | varchar |
Sample Data
| post_id | user_id |
|---|---|
| 1 | 101 |
| 2 | 102 |
| 3 | 103 |
| post_id | reaction_type |
|---|---|
| 1 | like |
| 1 | comment |
| 2 | like |
| 2 | like |
| 3 | like |
| post_id | rank |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
SQL Editor
| post_id | rank |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
Hints
Solution
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
Read the expected output columns to determine the final grain.
Aggregate or rank the input rows to calculate the requested metric.
Filter, sort, and alias the final columns to match the output.
Related Questions