1
+ -- Question 31
2
+ -- Table: Submissions
3
+
4
+ -- +---------------+----------+
5
+ -- | Column Name | Type |
6
+ -- +---------------+----------+
7
+ -- | sub_id | int |
8
+ -- | parent_id | int |
9
+ -- +---------------+----------+
10
+ -- There is no primary key for this table, it may have duplicate rows.
11
+ -- Each row can be a post or comment on the post.
12
+ -- parent_id is null for posts.
13
+ -- parent_id for comments is sub_id for another post in the table.
14
+
15
+
16
+ -- Write an SQL query to find number of comments per each post.
17
+
18
+ -- Result table should contain post_id and its corresponding number_of_comments,
19
+ -- 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
54
+ -- repeated in the table, we counted it only once.
55
+ -- The post with id 2 has two comments in the table with id 5 and 10.
56
+ -- The post with id 12 has no comments in the table.
57
+ -- The comment with id 6 is a comment on a deleted post with id 7 so we ignored it.
58
+
59
+ -- Solution
60
+ Select a .sub_id as post_id, coalesce(b .number_of_comments ,0 ) as number_of_comments
61
+ from (
62
+ select distinct sub_id from submissions where parent_id is null ) a
63
+ left join (
64
+ select parent_id, count (distinct(sub_id)) as number_of_comments
65
+ from submissions
66
+ group by parent_id
67
+ having parent_id = any(select sub_id from submissions where parent_id is null )) b
68
+ on a .sub_id = b .parent_id
69
+ order by post_id
0 commit comments