SQL 如何检查彼此之间是否存在一小时范围内的时间戳
SQL How do you check if there are any timestamps that are within one hour range between each other
我有一个 table 如下所示,其中用户事件记录为 unixtime
select day,
user_id,
unixtime,
from_unixtime(unixtime)
from sampletable
day
user_id
unixtime
timestamp
2020-12-20
1
1608434879
2020-12-20 03:27:59.000
2020-12-20
1
1608468153
2020-12-20 12:42:33.000
2020-12-20
2
1608436224
2020-12-20 03:50:24.000
2020-12-20
2
1608437616
2020-12-20 04:13:36.000
2020-12-20
3
1608476189
2020-12-20 14:56:29.000
2020-12-20
3
1608505424
2020-12-20 23:03:44.000
2020-12-20
3
1608505438
2020-12-20 23:03:58.000
2020-12-20
4
1608463622
2020-12-20 11:27:02.000
并且我想检查事件发生在彼此之间一小时内的用户数。
例如,
- 用户 1 不算在内,因为他的两个事件相隔 9 小时 15 分钟。
- user2 算作他的两个事件彼此之间的时间在 1 小时范围内。
- user3 也算在内。虽然他的第一场比赛和第二场比赛相隔8小时7分钟,但他的第二场比赛和第三场比赛相隔14秒。
- 用户 4 不算在内,因为该用户只执行了 1 个事件。
我希望我的最终结果看起来像:
day
total_user
number_of_qualified_user
2020-12-20
100
60
2020-12-21
123
82
2020-12-22
196
10
2020-12-23
111
28
2020-12-24
119
103
或
day
percentage_of_qualified_user
2020-12-20
60.00%
2020-12-21
66.67%
2020-12-22
5.10%
2020-12-23
25.22%
2020-12-24
86.55%
提前感谢您的帮助!
您可以使用 lead()
:
select day,
count(distinct case when next_unixtime - unixtime < 60*60 then user_id end) as num_users
from (select t.*,
lead(unixtime) over (partition by user_id, day order by unixtime) as next_unixtime
from sampletable
) t
group by day;
对于比率,您可以除以 count(distinct user_id)
。
我有一个 table 如下所示,其中用户事件记录为 unixtime
select day,
user_id,
unixtime,
from_unixtime(unixtime)
from sampletable
day | user_id | unixtime | timestamp |
---|---|---|---|
2020-12-20 | 1 | 1608434879 | 2020-12-20 03:27:59.000 |
2020-12-20 | 1 | 1608468153 | 2020-12-20 12:42:33.000 |
2020-12-20 | 2 | 1608436224 | 2020-12-20 03:50:24.000 |
2020-12-20 | 2 | 1608437616 | 2020-12-20 04:13:36.000 |
2020-12-20 | 3 | 1608476189 | 2020-12-20 14:56:29.000 |
2020-12-20 | 3 | 1608505424 | 2020-12-20 23:03:44.000 |
2020-12-20 | 3 | 1608505438 | 2020-12-20 23:03:58.000 |
2020-12-20 | 4 | 1608463622 | 2020-12-20 11:27:02.000 |
并且我想检查事件发生在彼此之间一小时内的用户数。
例如,
- 用户 1 不算在内,因为他的两个事件相隔 9 小时 15 分钟。
- user2 算作他的两个事件彼此之间的时间在 1 小时范围内。
- user3 也算在内。虽然他的第一场比赛和第二场比赛相隔8小时7分钟,但他的第二场比赛和第三场比赛相隔14秒。
- 用户 4 不算在内,因为该用户只执行了 1 个事件。
我希望我的最终结果看起来像:
day | total_user | number_of_qualified_user |
---|---|---|
2020-12-20 | 100 | 60 |
2020-12-21 | 123 | 82 |
2020-12-22 | 196 | 10 |
2020-12-23 | 111 | 28 |
2020-12-24 | 119 | 103 |
或
day | percentage_of_qualified_user |
---|---|
2020-12-20 | 60.00% |
2020-12-21 | 66.67% |
2020-12-22 | 5.10% |
2020-12-23 | 25.22% |
2020-12-24 | 86.55% |
提前感谢您的帮助!
您可以使用 lead()
:
select day,
count(distinct case when next_unixtime - unixtime < 60*60 then user_id end) as num_users
from (select t.*,
lead(unixtime) over (partition by user_id, day order by unixtime) as next_unixtime
from sampletable
) t
group by day;
对于比率,您可以除以 count(distinct user_id)
。