SQL:有效地计算花费的时间

时间:2017-07-08 03:17:55

标签: sql postgresql select join group-by

给定一个事件时间戳列表,您如何计算“花费的时间”? “花费的时间”是每个时间戳之间的时间间隔的总和,忽略高于某个阈值的间隔,例如, 1分钟,在此期间用户可能处于非活动状态。

我试过这样的事情:

select sum(finish - start)
from (select start.time as start,
             finish.time as finish
      from events start, events finish
      where start.time < finish.time and
            finish.time - start.time < interval '1 minute'
      group by start.time) as intervals;

但事实证明这种效率极低,而且从未终止过。

2 个答案:

答案 0 :(得分:2)

使用:

SELECT SUM ( time_interval_up_to_1_min )
FROM (
  SELECT 
        CASE WHEN time - lag( time ) over (ORDER BY time) 
                <= interval '1' minute
             THEN time - lag( time ) over (ORDER BY time)
        END As time_interval_up_to_1_min
  FROM events
) x

演示:http://sqlfiddle.com/#!17/6f814/7

答案 1 :(得分:1)

select sum(time-lag(time) over (order by time)) from events

我不确定你为什么以这种方式加入事件,但这很可能是为什么查询永远在运行,而不是因为琐碎的聚合计算。