Number Of Comments Per Post Problem


Description

LeetCode Problem 1241.

Table: Submissions

1
2
3
4
5
6
7
8
9
10
+---------------+----------+
| Column Name   | Type     |
+---------------+----------+
| sub_id        | int      |
| parent_id     | int      |
+---------------+----------+
There is no primary key for this table, it may have duplicate rows.
Each row can be a post or comment on the post.
parent_id is null for posts.
parent_id for comments is sub_id for another post in the table.

Write an SQL query to find number of comments per each post.

Result table should contain post_id and its corresponding number_of_comments, and must be sorted by post_id in ascending order.

Submissions may contain duplicate comments. You should count the number of unique comments per post.

Submissions may contain duplicate posts. You should treat them as one post.

The query result format is in the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Submissions table:
+---------+------------+
| 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          |
+---------+------------+

Result table:
+---------+--------------------+
| post_id | number_of_comments |
+---------+--------------------+
| 1       | 3                  |
| 2       | 2                  |
| 12      | 0                  |
+---------+--------------------+

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.


MySQL Solution

1
2
3
4
5
6
7
select s1.sub_id as post_id,
    count(distinct s2.sub_id) as number_of_comments
from Submissions s1
left join Submissions s2
on s2.parent_id = s1.sub_id
where s1.parent_id is null
group by s1.sub_id




Related Posts

Report Contiguous Dates Problem

LeetCode 1225. Write an SQL query to generate a report...

Monthly Transactions II Problem

LeetCode 1205. Write an SQL query to find for each...

Team Scores In Football Tournament Problem

LeetCode 1212. Write an SQL query that selects the team_id,...

Last Person To Fit In The Elevator Problem

LeetCode 1204. Write an SQL query to find the person_name...

Queries Quality And Percentage Problem

LeetCode 1211. Write an SQL query to find each query_name,...

Number Of Comments Per Post Problem

LeetCode 1241. Write an SQL query to find number of...