表中数据如下:
要求相邻2条记录 如第1条和第2条记录创建时间差统计出来
即
zhouhui 5秒
dingxiang 24秒
需求出来了需要解决,后来找到解决办法了
方法 1:
Sql代码
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:
Sql代码
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
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,