[英]How to find the second minimum log in time per each user id
I'm working on a SQL query on BigQuery and trying to find the second minimum login time for each user id.我正在 BigQuery 上进行 SQL 查询,并试图为每个用户 ID 找到第二个最短登录时间。
User_id![]() |
LoginTime![]() |
---|---|
1 ![]() |
2022-11-06 08:45:17 ![]() |
1 ![]() |
2022-11-07 09:52:27 ![]() |
1 ![]() |
2022-11-08 02:08:54 ![]() |
2 ![]() |
2022-11-04 08:10:38 ![]() |
2 ![]() |
2022-11-07 16:46:34 ![]() |
2 ![]() |
2022-11-18 01:26:53 ![]() |
And I want to find the following result.我想找到以下结果。
User_id![]() |
SecondLoginTime![]() |
---|---|
1 ![]() |
2022-11-07 09:52:27 ![]() |
2 ![]() |
2022-11-07 16:46:34 ![]() |
Could anyone help me figure out how to approach this problem?谁能帮我弄清楚如何解决这个问题?
We can use the RANK()
analytic function:我们可以使用
RANK()
分析函数:
WITH cte AS (
SELECT *, RANK() OVER (PARTITION BY User_id ORDER BY LoginTime) rnk
FROM yourTable
)
SELECT User_id, LoginTime AS SecondLoginTime
FROM cte
WHERE rnk = 2
ORDER BY User_id;
Note that, depending on the behavior you want if ties can happen, you may want to use DENSE_RANK()
instead of RANK()
.请注意,根据您想要的行为,如果关系可能发生,您可能想要使用
DENSE_RANK()
而不是RANK()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.