Table Schema
Inspect
Table
| Column | Type |
|---|---|
| post_id | integer |
| user_id | integer |
| Column | Type |
|---|---|
| post_id | integer |
| reaction_id | integer |
Find the user who generated the highest total engagement.
Table Schema
| Column | Type |
|---|---|
| post_id | integer |
| user_id | integer |
| Column | Type |
|---|---|
| post_id | integer |
| reaction_id | integer |
Sample Data
| post_id | user_id |
|---|---|
| 1 | 101 |
| 2 | 102 |
| 3 | 101 |
| post_id | reaction_id |
|---|---|
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| 3 | 5 |
| 3 | 6 |
| user_id | total_engagement |
|---|---|
| 101 | 5 |
SQL Editor
| user_id | total_engagement |
|---|---|
| 101 | 5 |
Hints
Solution
Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.
SELECT p.user_id, COUNT(r.reaction_id) AS total_engagement FROM posts p JOIN reactions r ON p.post_id = r.post_id GROUP BY p.user_id ORDER BY total_engagement DESC LIMIT 1;
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