如何在 SQL 中找到每个用户每小时的评论数?

How can I find count of comments per user per hour in SQL?

我有两个表:

表 1

post_id  | num_comments
3421     | 1
6472     | 3
7294     | 0
4891     | 4

表 2

post_id  | user_id | timestamp
3421     | 100     | 2022-03-30 06:47:30.000000000
6472     | 100     | 2022-03-30 06:48:00.000000000
6472     | 101     | 2022-03-30 06:52:30.000000000
6472     | 101     | 2022-03-30 06:53:30.000000000
4891     | 102     | 2022-03-30 06:57:30.000000000
4891     | 102     | 2022-03-30 06:59:30.000000000
4891     | 103     | 2022-03-30 06:59:45.000000000
4891     | 104     | 2022-03-30 07:01:00.000000000

如您所见,每个 post_id 可以分配多个 user_id。 我需要找到每小时 user_id 的评论数。

我试过下面的代码,但它只给我每小时 post 的评论数,而不是每个用户的评论数。我需要每个用户每小时的计数。

select t1.user_id, date_part(hour, t2.timestamp) as hour, 
    count(t2.num_comments) as comments
from Table1 t1 join Table2 t2 
    on t1.post_id = t2.post_id
group by t1.user_id, t2.timestamp;

按用户和小时汇总:

SELECT t1.user_id, DATE_FORMAT(t2.timestamp, '%Y-%m-%d %H:00:00') AS hour,
       COUNT(t2.num_comments) AS comments
FROM Table1 t1
INNER JOIN Table2 t2
    ON t1.post_id = t2.post_id
GROUP BY 1, 2;

请注意,如果您想保证两个特定日期之间的每个小时都会出现在您的报告中,而您的数据可能没有每个小时都存在,那么您将必须使用称为日历 table 的东西,它是一个 table 包含您想要显示的所有 dates/hours。