|
1 |
| ---1241. Number of Comments per Post |
2 |
| --- |
3 |
| ---Table: Submissions |
4 |
| --- |
5 |
| ---+---------------+----------+ |
6 |
| ---| Column Name | Type | |
7 |
| ---+---------------+----------+ |
8 |
| ---| sub_id | int | |
9 |
| ---| parent_id | int | |
10 |
| ---+---------------+----------+ |
11 |
| ---There is no primary key for this table, it may have duplicate rows. |
12 |
| ---Each row can be a post or comment on the post. |
13 |
| ---parent_id is null for posts. |
14 |
| ---parent_id for comments is sub_id for another post in the table. |
15 |
| --- |
16 |
| --- |
17 |
| ---Write an SQL query to find number of comments per each post. |
18 |
| --- |
19 |
| ---Result table should contain post_id and its corresponding number_of_comments, and must be sorted by post_id in ascending order. |
20 |
| --- |
21 |
| ---Submissions may contain duplicate comments. You should count the number of unique comments per post. |
22 |
| --- |
23 |
| ---Submissions may contain duplicate posts. You should treat them as one post. |
24 |
| --- |
25 |
| ---The query result format is in the following example: |
26 |
| --- |
27 |
| ---Submissions table: |
28 |
| ---+---------+------------+ |
29 |
| ---| sub_id | parent_id | |
30 |
| ---+---------+------------+ |
31 |
| ---| 1 | Null | |
32 |
| ---| 2 | Null | |
33 |
| ---| 1 | Null | |
34 |
| ---| 12 | Null | |
35 |
| ---| 3 | 1 | |
36 |
| ---| 5 | 2 | |
37 |
| ---| 3 | 1 | |
38 |
| ---| 4 | 1 | |
39 |
| ---| 9 | 1 | |
40 |
| ---| 10 | 2 | |
41 |
| ---| 6 | 7 | |
42 |
| ---+---------+------------+ |
43 |
| --- |
44 |
| ---Result table: |
45 |
| ---+---------+--------------------+ |
46 |
| ---| post_id | number_of_comments | |
47 |
| ---+---------+--------------------+ |
48 |
| ---| 1 | 3 | |
49 |
| ---| 2 | 2 | |
50 |
| ---| 12 | 0 | |
51 |
| ---+---------+--------------------+ |
52 |
| --- |
53 |
| ---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. |
54 |
| ---The post with id 2 has two comments in the table with id 5 and 10. |
55 |
| ---The post with id 12 has no comments in the table. |
56 |
| ---The comment with id 6 is a comment on a deleted post with id 7 so we ignored it. |
57 |
| --- |
58 |
| ---# Write your MySQL query statement below |
59 |
| - |
60 | 1 | select s.sub_id as post_id,
|
61 | 2 | (select count(distinct(s1.sub_id)) from Submissions s1 where s1.parent_id = s.sub_id) as number_of_comments
|
62 | 3 | from Submissions s
|
|
0 commit comments