我有一个包含三列(用户,时间戳,活动)的表。活动基本上是入住或退房。如何生成查询以查看用户白天计时的总秒数?
系统存在一个问题,有时会有两个检查但只有一个检出...在这种情况下我想只采用最低的时间戳检查。
我想出了类似的东西(活动:1 =登记入住,0 =结帐):
select a.user_id, a.d, time_to_sec(TIMEDIFF(b.created_at, a.created_at)) total_secs,
a.created_at check_in, b.created_at check_out
from (select user_id, created_at, date(created_at) d, @rownum := @rownum + 1 AS num from table, (SELECT @rownum := 0) r where activity = 1 order by user_id, created_at) a
join (select user_id, created_at, date(created_at) d, @rownum2 := @rownum2 + 1 AS num from table, (SELECT @rownum2 := 0) r where activity = 0 order by user_id, created_at) b
on a.user_id = b.user_id and a.d = b.d and a.num = b.num
但是,我认为依赖rownum并非累积
答案 0 :(得分:0)
如果我正确理解您的要求,您需要在结账时和之前的最早登记之间的秒数,但需要在上一次结帐之后。
所以你需要的是一个查询,它将结账与之前的结账相结合,然后在这两项活动之间进行最早的登记。
select
curr_co.user_id,
curr_co.created_at,
max(prev_co.created_at)
from
table as curr_co
left outer join
table as prev_co
on (curr_co.user_id = prev_co.user_id and curr_co.created_at > prev_co.created_at and curr_co.activity = _checkout_ and prev_co.activity = _checkout_)
group by curr_co.user_id, curr_co.created_at
此查询应该为您提供每位用户以前结帐的结帐清单。
现在选择介于两者之间的所有签到和最小值并计算差异。
select ... min(ci.created_at), time_to_sec(TIMEDIFF(min(ci.created_at), curr_co.created_at))
... join
table as ci
on (ci.user_id = curr_co.user_id and ci.created_at < curr_co.created_at and ci.created_at > prev_co.created_at and ci.activity = _check-in_)