Number of Comments per Post - Problem
Imagine you're building a social media analytics dashboard that needs to track engagement metrics! You have a database table called Submissions that contains both posts and comments in a hierarchical structure.
Here's how it works:
- Each row represents either a post or a comment
- Posts have
parent_id = NULL(they're the root of the conversation) - Comments have
parent_idpointing to a post'ssub_id
Your mission: Calculate how many unique comments each post has received. The table might contain duplicate posts (treat as one) and duplicate comments (count unique ones only).
Expected Output: A result table with post_id and number_of_comments, ordered by post_id ascending.
Input & Output
example_1.sql โ Basic Case
$
Input:
Submissions table:
| sub_id | parent_id |
|--------|----------|
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | null |
| 5 | 4 |
| 6 | 4 |
โบ
Output:
| post_id | number_of_comments |
|---------|-------------------|
| 1 | 2 |
| 4 | 2 |
๐ก Note:
Post 1 has comments 2 and 3 (2 total). Post 4 has comments 5 and 6 (2 total). Results ordered by post_id ascending.
example_2.sql โ Duplicate Comments
$
Input:
Submissions table:
| sub_id | parent_id |
|--------|----------|
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 2 | 1 |
| 4 | null |
โบ
Output:
| post_id | number_of_comments |
|---------|-------------------|
| 1 | 2 |
| 4 | 0 |
๐ก Note:
Post 1 has duplicate comment 2, but we count only unique comments (2, 3). Post 4 has no comments.
example_3.sql โ No Comments
$
Input:
Submissions table:
| sub_id | parent_id |
|--------|----------|
| 1 | null |
| 2 | null |
| 3 | null |
โบ
Output:
| post_id | number_of_comments |
|---------|-------------------|
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
๐ก Note:
All entries are posts with no comments. Each post has 0 comments.
Constraints
- 1 โค Number of submissions โค 1000
- 1 โค sub_id โค 105
- parent_id is null for posts, valid sub_id for comments
- The table may contain duplicate rows
- Results must be ordered by post_id in ascending order
Visualization
Tap to expand
Understanding the Visualization
1
Identify Posts
Find all unique posts (entries with parent_id = NULL)
2
Match Comments
For each post, find all comments that reference it as parent
3
Count Unique
Count distinct comment IDs to handle duplicates
4
Generate Report
Present results ordered by post ID for consistent reporting
Key Takeaway
๐ฏ Key Insight: SQL's aggregation functions (GROUP BY + COUNT DISTINCT) handle complex data relationships efficiently in a single query, making it ideal for analytics reporting where duplicate handling and grouping are essential.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code