使用SQL如何找到每个用户会话之间的持续时间或时间?例如,user_id 1234在2017-01-01 00:00:00有一个会话,2017-01-02有另一个会话(见下表)。如何找到上一个session_end到下一个session_start开始之间的时间。
user_id|session_start |session_end
1234 | 2017-01-01 00:00:00| 2017-01-01 00:30:30
1236 | 2017-01-01 01:00:00| 2017-01-01 01:05:30
1234 | 2017-01-02 12:00:09| 2017-01-02 12:00:30
1234 | 2017-01-01 02:00:00| 2017-01-01 03:30:30
1236 | 2017-01-01 00:00:00| 2017-01-01 00:30:30
感谢。
答案 0 :(得分:2)
select user_id, session_start, session_end,
session_start - lag(session_end) over (partition by user_id order by session_start) as time_diff
from the_table
order by user_id, session_start;
在线示例:http://rextester.com/NTVH38963
从另一个时间戳中减去一个时间戳会返回interval
以将其转换为分钟,您可以extract获取间隔所代表的秒数并将它们除以60得到分钟:
select user_id, session_start, session_end,
extract(epoch from
session_start - lag(session_end) over (partition by user_id order by session_start)
) / 60 as minutes
from the_table
order by user_id, session_start;
答案 1 :(得分:1)
以下是使用子查询执行此操作的一种方法:
SELECT dT.user_ID
,dT.max_session_start
,DATEDIFF(minute, (SELECT MAX(session_end)
FROM tablename T
WHERE T.user_ID = dT.user_ID
AND T.session_end < dT.max_session_start)
, dT.max_session_start
) AS minutes
FROM (
SELECT user_ID
,MAX(session_start) AS max_session_start
FROM tablename
GROUP BY user_ID
) AS dT