如何计算用户相隔1天的会话数?这就是我到目前为止所拥有的。答案应为46,但此代码仅返回最后排名的记录以及它与第一条记录之间的差异。我想把数字46作为正确的输出。
set @pk1 =''; set @rn1 = 1; set @days = '';
select c.user_id, c.day_session, datediff(d.day_session, c.day_session)
from
(select user_id, day_session, rank
FROM
(select user_id, day_session,
@rn1 := if(@pk1=user_id, if(@days=day_session, @rn1, @rn1+1),1) as rank,
@pk1 := user_id,
@days := @day_session
from
(select user_id, date(reg_utc_timestamp) AS day_session
from mobile_traffic
where user_id = 'abcdxyz'
group by 1,2) a) b) c
inner join (select user_id, day_session, rank
FROM
(select user_id, day_session,
@rn1 := if(@pk1=user_id, if(@days=day_session, @rn1, @rn1+1),1) as rank,
@pk1 := user_id,
@days := @day_session
from
(select user_id, date(reg_utc_timestamp) AS day_session
from mobile_traffic
where user_id = 'abcdxyz'
group by 1,2) x) y) d on c.user_id = d.user_id and d.rank = c.rank + 1
当我运行这个片段时,我得到了46条记录。
set @pk1 ='';
set @rn1 = 1;
set @days = '';
select Respondent_ID, day_session, rank
FROM
(select user_id,
day_session,
@rn1 := if(@pk1=user_id, if(@days=day_session, @rn1, @rn1+1),1) as rank,
@pk1 := user_id,
@days := @day_session
from
(select user_id, date(reg_utc_timestamp) AS day_session
from mobile_traffic
where user_id = 'abcdxyz'
group by 1,2) a) b
以下是此用户的示例数据:
abcdxyz 2017-11-19 1
abcdxyz 2017-11-20 2
abcdxyz 2017-11-21 3
abcdxyz 2017-11-22 4
abcdxyz 2017-11-23 5
abcdxyz 2017-11-24 6
abcdxyz 2017-11-27 7
abcdxyz 2017-11-28 8
abcdxyz 2017-11-29 9
abcdxyz 2017-11-30 10
abcdxyz 2017-12-01 11
abcdxyz 2017-12-02 12
abcdxyz 2017-12-03 13
abcdxyz 2017-12-04 14
abcdxyz 2017-12-05 15
abcdxyz 2017-12-06 16
abcdxyz 2017-12-07 17
abcdxyz 2017-12-08 18
abcdxyz 2017-12-09 19
abcdxyz 2017-12-10 20
abcdxyz 2017-12-11 21
abcdxyz 2017-12-12 22
abcdxyz 2017-12-13 23
abcdxyz 2017-12-14 24
abcdxyz 2017-12-15 25
abcdxyz 2017-12-16 26
abcdxyz 2017-12-17 27
abcdxyz 2017-12-18 28
abcdxyz 2017-12-19 29
abcdxyz 2017-12-20 30
abcdxyz 2017-12-21 31
abcdxyz 2017-12-22 32
abcdxyz 2017-12-23 33
abcdxyz 2017-12-24 34
abcdxyz 2017-12-25 35
abcdxyz 2017-12-26 36
abcdxyz 2017-12-27 37
abcdxyz 2017-12-28 38
abcdxyz 2017-12-29 39
abcdxyz 2017-12-30 40
abcdxyz 2017-12-31 41
abcdxyz 2018-01-01 42
abcdxyz 2018-01-02 43
abcdxyz 2018-01-03 44
abcdxyz 2018-01-04 45
abcdxyz 2018-01-05 46
答案 0 :(得分:0)
我认为解决方案是在相关日期前一天的记录上使用联接。试试这个:
SELECT COUNT(*) FROM mobile_traffic m1
INNER JOIN mobile_traffic m2 ON m1.user_id = m2.user_id
AND DATE(m1.reg_utc_timestamp) =
(DATE(m2.reg_utc_timestamp) + INTERVAL 1 DAY)
WHERE m1.user_id = <some_user_id>