Number of Comments per Post - Problem
Given a Submissions table that contains posts and comments, find the number of comments per post.
The table structure:
sub_id: Unique identifier for each submissionparent_id:NULLfor posts, referencessub_idof the parent post for comments
Requirements:
- Count only unique comments per post (ignore duplicate comments)
- Treat duplicate posts as one post
- Return
post_idandnumber_of_comments - Order results by
post_idin ascending order
Table Schema
Submissions
| Column Name | Type | Description |
|---|---|---|
sub_id
PK
|
int | Unique identifier for submission (post or comment) |
parent_id
|
int | NULL for posts, sub_id of parent post for comments |
Primary Key: sub_id
Note: Table may contain duplicate rows. Posts have parent_id = NULL, comments reference parent post via parent_id
Input & Output
Example 1 — Basic Posts and Comments
Input Table:
| sub_id | parent_id |
|---|---|
| 1 | |
| 2 | 1 |
| 3 | 1 |
| 4 | |
| 5 | 4 |
Output:
| post_id | number_of_comments |
|---|---|
| 1 | 2 |
| 4 | 1 |
💡 Note:
Post 1 has 2 comments (submissions 2 and 3). Post 4 has 1 comment (submission 5). Results are ordered by post_id ascending.
Example 2 — Duplicate Submissions
Input Table:
| sub_id | parent_id |
|---|---|
| 1 | |
| 1 | |
| 2 | 1 |
| 2 | 1 |
| 3 |
Output:
| post_id | number_of_comments |
|---|---|
| 1 | 1 |
| 3 | 0 |
💡 Note:
Duplicate posts (1,1) are treated as one post. Duplicate comments (2,2) are counted as one unique comment. Post 3 has no comments so count is 0.
Example 3 — No Comments Case
Input Table:
| sub_id | parent_id |
|---|---|
| 1 | |
| 2 |
Output:
| post_id | number_of_comments |
|---|---|
| 1 | 0 |
| 2 | 0 |
💡 Note:
Both posts have no comments, so number_of_comments is 0 for each post.
Constraints
-
1 ≤ sub_id ≤ 1000 -
parent_idisNULLfor posts or references a validsub_id - Table may contain duplicate rows
Visualization
Tap to expand
Understanding the Visualization
1
Identify Posts
Filter rows where parent_id IS NULL
2
Join Comments
LEFT JOIN to match comments with posts
3
Count & Group
GROUP BY post and COUNT DISTINCT comments
Key Takeaway
🎯 Key Insight: Use self-join pattern when relating rows within the same table (posts ↔ comments)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code