我有一个记录登录/注销的表。模式和示例数据:http://sqlfiddle.com/#!2/e1b35/1
我需要创建存储过程,它将打印(注销-登录)用户和日期(使用用户的应用程序在日期的持续时间)的次数之和。在列中,类型I表示登录和O注销。
入参:@username,@date。输出: time。
发布于 2012-12-11 03:38:41
您需要标识彼此相关的所有登录组。我这样做的方法是找到与登录相关联的注销。您正在处理日志数据,因此,如果有多个登录而没有注销,请不要惊讶。
select l.*,
(select min(l2.time) from logs l2 where l2.username = l.username and l2.type = 'O' and l2.time > l.time
) as logoutTime
from logs l
where l.type = 'I'现在,您可以将用户名和LogoutTime作为一对进行聚合,以获得您想要的内容:
select username, logoutTime, min(time) as StartTime, logouttime as EndTime,
datediff(s, min(time), logoutTime) as TimeInSeconds
from (select l.*,
(select min(l2.time) from logs l2 where l2.username = l.username and l2.type = 'O' and l2.time > l.time
) as logoutTime
from logs l
where l.type = 'I'
) l
group by username, logoutTime请注意,您将SQL Server指定为标记,但SQL文件用于MySQL;日期函数在不同的数据库中往往是不同的。
而且,如果您使用的是SQL Server 2012,还有一种更简单的方法。如果是这种情况,您应该指定它。
发布于 2012-12-11 06:02:38
这是戈登·林诺夫的解决方案,经过修改,它不包括最外层的聚合,并使用更清晰的别名,IMO
select username,time_in,time_out_min,
datediff(s, time_in, time_out_min) as TimeInSeconds
from (
select i.username, i.time as time_in,
(select min(o.time) as min_time_out
from logs o
where o.username = i.username and
o.type = 'O' and
o.time > i.time
) as time_out_min
from logs i
where i.type = 'I'
) d;https://stackoverflow.com/questions/13807534
复制相似问题