PostgreSQL - 帮助总结选定时期

时间:2015-06-11 20:20:26

标签: sql postgresql nested

我正在尝试确定在选定时间段内登录的时间量,例如一周。显然,这并不一定意味着它落在规定的日子;这些可以在几天之间破坏,所以有人可以在10日晚上8点登录,并在11日凌晨4点退出。我希望这意味着他们已经登录了8个小时。

我有以下SQL关闭,但在同一天没有显示多个登录和退出:

    select user,date_part('epoch', sum(times)) * INTERVAL '1 second' as hours
from (

  select d.user,run.create_ts - 
    (   select cm.create_ts 
        from OUTGOING_MESSAGE cm,
        users d1,
        CHAT_DIALOG DC1
        where dialog_id=DC1.id
        and DC1.user_id=d1.id
        and d1.user=d.user
        and cm.create_ts > run.create_ts and cm.message = 'logged out'
        order by cm.create_ts limit 1
    ) times
  from OUTGOING_MESSAGE run,
  users d,
  CHAT_DIALOG DC
  where run.dialog_id=DC.id
  and DC.user_id=D.id
  and run.message = 'logged in'
  and run.create_ts between current_date-7 and current_date
  and ( select message 
        from OUTGOING_MESSAGE 
        where create_ts < run.create_ts 
    order by create_ts desc limit 1) <> 'logged in'
  group by d.user, run.create_ts


) a
group by callsign
order by callsign Asc

目前的结果:

实际:

用户|小时

01 | -17:16:25.979

预期结果(手动计算)

用户|小时

01 | 22:15

谢谢大家。

0 个答案:

没有答案