? 下午看到项目有个统计报表的生成,其中XX表中记录相邻2条记录统计时间差 即
?? 表中数据如下:
?要求相邻2条记录 如第1条和第2条记录创建时间差统计出来
? 即
????????? zhouhui???????? 5秒
????????? dingxiang???? 24秒
?
需求出来了需要解决,后来找到解决办法了
方法 1:
?
select t.username,(max( t.CREATIONDATE)-min(t.CREATIONDATE))*24*60*60,count(t.username)/2 from ofloginlog t --where USERNAME = 'zhouhui' group by t.username
?? 通过分组 统计出用户在线时长(即前后2条记录作差)
?? 效果图:
???
说明 最后一个字段我是用来统计 用户登录次数使用的。
?????? oracle 两个时间相减默认的是天数
?????? oracle 两个时间相减默认的是天数*24 为相差的小时数
?????? oracle 两个时间相减默认的是天数*24*60 为相差的分钟数
?????? oracle 两个时间相减默认的是天数*24*60*60 为相差的秒数
方法2:
?
select username, sum(b), count(username) / 2 from (select id, username, (CREATIONDATE - lgtime) * 24 * 60 * 60 as b from (select t.*, lag(type) over(partition by username order by CREATIONDATE) lgtype, lag(CREATIONDATE) over(partition by username order by CREATIONDATE) lgtime from ofloginlog t)) -- where USERNAME = 'zhouhui') group by username
?? 实现效果 一样 这里不帖了
?? 又复习了一下基本的SQL 了 呵呵
20100520 需求有些变更 要求统计个数不是统计TYPE 1 和0 记录之和均值,只统计TYPE=0 的值,
这样SQL 的分组就不能这样了,想了一下改进了SQL
select g.username, g.time, h.count from (select t.username, floor((max(t.CREATIONDATE) - min(t.CREATIONDATE)) * 24 * 60 * 60) as time from ofloginlog t, ofuser b where 1 = 1 and t.username = b.username group by t.username) g, (select t.username, count(t.username) as count from ofloginlog t where t.type = '0' group by t.username) h where g.username = h.username order by count desc
??? 查询结果
???
?分析 时间差是2个集合之间的差,而后面统计个数只是单独限制条件是TYPE=0的记录数,统计的数据个数就不一致,所以很难一个分组实现,思路是先实现 USERNAME 和TIME 的记录 在统计USERNAME和满足TYPE=0的记录个数 将2个结果合并 通过? SELECT? XX? FROM?? A? B 2个临时表的内联关系实现合并结果集合