关于统计登陆时长的一个sql--------一定要学好sql

来源:互联网 发布:linux关闭防火墙命令 编辑:程序博客网 时间:2024/05/19 11:35

前天,碰到这么一个问题,大概是这样的,需要统计一个用户的历史的登录时长、

表设计是这样的:id (主键,自增),userId(用户id),updTime(登陆时间/退出时间),flag(标识位,退出/登陆),需要计算一个用户的历史登陆情况,字段有用户id,登陆时间,退出时间,在线时长。其实,如果表这么设计的话,id,userId,logOnTime,logOffTime,flag,这个事情就好办了,但是,表已经设计成这样了,暂且把修改表结构的想法放到一边,先看一下解决方案:

 

=========================================================

oracle解决方案

 

select
    t1.userId,
    t1.updTime qi,
    t2.updTime zhong,
    ROUND(TO_NUMBER(t2.updTime - t1.updTime * 24) hour,
    ROUND(TO_NUMBER(t2.updTime- t1.updTime) * 24*60) mi,
    ROUND(TO_NUMBER(t2.updTime - t1.updTime) * 24*60*60) ss
from
    login t1,
    login t2
where
    t1.userId=t2.userId and
    t1.flag=1 and
    t2.flag=0 and
    t1.updTime <t2.updTime and
    t2.id=(select min(id) from login where userId=t1.userId and flag=0 and id>t1.id)
order by t1.id

 

===============================================================

 

db2解决方案

 

select
    t1.userId,
    t1.updTime  as  logOnTime,
    t2.updTime  as logOffTime,
    timestampdiff(2,char(t2.updTime-t1.updTime)) as onLineTime
from
    login t1,
    login t2
where
    t1.userId=t2.userId and
    t1.flag=1 and
    t2.flag=0 and
    t1.updTime<t2.updTime and
    t2.id=(select min(t3.id) from login t3 where t3.userId= t1.userId and t3.flag=0 and t3.id>t1.id)
order by t1.id

 

 

 

 

 

原创粉丝点击