首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从日志表中获取用户使用app的时长

从日志表中获取用户使用app的时长
EN

Stack Overflow用户
提问于 2012-12-11 03:10:54
回答 2查看 85关注 0票数 0

我有一个记录登录/注销的表。模式和示例数据:http://sqlfiddle.com/#!2/e1b35/1

我需要创建存储过程,它将打印(注销-登录)用户和日期(使用用户的应用程序在日期的持续时间)的次数之和。在列中,类型I表示登录和O注销。

入参:@username,@date。输出: time。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-11 03:38:41

您需要标识彼此相关的所有登录组。我这样做的方法是找到与登录相关联的注销。您正在处理日志数据,因此,如果有多个登录而没有注销,请不要惊讶。

代码语言:javascript
运行
复制
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作为一对进行聚合,以获得您想要的内容:

代码语言:javascript
运行
复制
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,还有一种更简单的方法。如果是这种情况,您应该指定它。

票数 1
EN

Stack Overflow用户

发布于 2012-12-11 06:02:38

这是戈登·林诺夫的解决方案,经过修改,它不包括最外层的聚合,并使用更清晰的别名,IMO

代码语言:javascript
运行
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13807534

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档