Description
Table: Submissions
| Column Name | Type |
|---|---|
| sub_id | int |
| parent_id | int |
- This table may have duplicate rows.
- Each row can be a post or comment on the post.
parent_idisnullfor posts.parent_idfor comments issub_idfor another post in the table.
Problem Statement
Write a solution to find the number of comments per post. The result table should contain post_id and its corresponding number_of_comments.
- The
Submissionstable may contain duplicate comments. You should count the number of unique comments per post. - The
Submissionstable may contain duplicate posts. You should treat them as one post.
The result table should be ordered by post_id in ascending order.
The result format is in the following example.
Example 1:
Input:
Submissionstable:
| sub_id | parent_id |
|---|---|
| 1 | Null |
| 2 | Null |
| 1 | Null |
| 12 | Null |
| 3 | 1 |
| 5 | 2 |
| 3 | 1 |
| 4 | 1 |
| 9 | 1 |
| 10 | 2 |
| 6 | 7 |
Output:
| post_id | number_of_comments |
|---|---|
| 1 | 3 |
| 2 | 2 |
| 12 | 0 |
Explanation:
- The post with id 1 has three comments in the table with id 3, 4, and 9. The comment with id 3 is repeated in the table, we counted it only once.
- The post with id 2 has two comments in the table with id 5 and 10.
- The post with id 12 has no comments in the table.
- The comment with id 6 is a comment on a deleted post with id 7 so we ignored it.
Solution
First you need to find the posts. For this you can filter the table with rows where parent_id IS NULL.
1WITH posts AS (
2 SELECT DISTINCT sub_id
3 FROM Submissions
4 WHERE parent_id IS NULL
5)
The next step is to find distinct sub_id grouped by post_id from the above posts view. For this you will have to join with Submissions table.
1SELECT p.sub_id AS post_id, COUNT(DISTINCT s.sub_id) AS number_of_comments
2 FROM posts p
3 LEFT JOIN Submissions s ON p.sub_id = s.parent_id
4 GROUP BY p.sub_id
Finally, you need to order the results by sub_id. The final solution looks like this.
1WITH posts AS (
2 SELECT DISTINCT sub_id
3 FROM Submissions
4 WHERE parent_id IS NULL
5) SELECT p.sub_id AS post_id, COUNT(DISTINCT s.sub_id) AS number_of_comments
6 FROM posts p
7 LEFT JOIN Submissions s ON p.sub_id = s.parent_id
8 GROUP BY p.sub_id
9 ORDER By p.sub_id


Comments