sql 相邻2条记录时间差比较

转载地址:http://wwwzhouhui.iteye.com/blog/614147

  下午看到项目有个统计报表的生成,其中XX表中记录相邻2条记录统计时间差 即

   表中数据如下:



 要求相邻2条记录 如第1条和第2条记录创建时间差统计出来

  即

          zhouhui         5秒

          dingxiang     24秒

 

需求出来了需要解决,后来找到解决办法了

方法 1:

 

Sql代码   收藏代码
  1. select t.username,(max( t.CREATIONDATE)-min(t.CREATIONDATE))*24*60*60,count(t.username)/2  
  2.   from ofloginlog t  
  3.  --where USERNAME = 'zhouhui'  
  4.  group by t.username  

   通过分组 统计出用户在线时长(即前后2条记录作差)

   效果图:

    

说明 最后一个字段我是用来统计 用户登录次数使用的。

       oracle 两个时间相减默认的是天数

       oracle 两个时间相减默认的是天数*24 为相差的小时数

       oracle 两个时间相减默认的是天数*24*60 为相差的分钟数

       oracle 两个时间相减默认的是天数*24*60*60 为相差的秒数

方法2:

 

Sql代码   收藏代码
  1. select username, sum(b), count(username) / 2  
  2.    from (select id, username, (CREATIONDATE - lgtime) * 24 * 60 * 60 as b  
  3.            from (select t.*,  
  4.                         lag(type) over(partition by username order by CREATIONDATE) lgtype,  
  5.                         lag(CREATIONDATE) over(partition by username order by CREATIONDATE) lgtime  
  6.                    from ofloginlog t))  
  7.  -- where USERNAME = 'zhouhui')  
  8.   group by username  

   实现效果 一样 这里不帖了

   又复习了一下基本的SQL 了 呵呵

20100520 需求有些变更 要求统计个数不是统计TYPE 1 和0 记录之和均值,只统计TYPE=0 的值,

这样SQL 的分组就不能这样了,想了一下改进了SQL

Sql代码   收藏代码
  1. select g.username, g.time, h.count  
  2.    from (select t.username,  
  3.                 floor((max(t.CREATIONDATE) - min(t.CREATIONDATE)) * 24 * 60 * 60) as time  
  4.            from ofloginlog t, ofuser b  
  5.           where 1 = 1  
  6.             and t.username = b.username  
  7.           group by t.username) g,  
  8.         (select t.username, count(t.username) as count  
  9.            from ofloginlog t  
  10.           where t.type = '0'  
  11.           group by t.username) h  
  12.   where g.username = h.username  
  13.   order by count desc  

    查询结果

    

 分析 时间差是2个集合之间的差,而后面统计个数只是单独限制条件是TYPE=0的记录数,统计的数据个数就不一致,所以很难一个分组实现,思路是先实现 USERNAME 和TIME 的记录 在统计USERNAME和满足TYPE=0的记录个数 将2个结果合并 通过  SELECT  XX  FROM   A  B 2个临时表的内联关系实现合并结果集合

猜你喜欢

转载自blog.csdn.net/qq_34664202/article/details/80680750