Postgresql组通过重复项目

时间:2018-02-18 21:38:48

标签: postgresql group-by lag partition-by

我正在使用postgresql来存储来自RTLS平台的历史数据。 不连续收集位置数据。 historical_movements实现为单个表,如下所示(它是一个简化的表,但足以呈现用例):

User   Area   EnterTime               ExitTime
John   room1  2018-01-01 10:00:00     2018-01-01 10:00:05
Doe    room1  2018-01-01 10:00:00     2018-01-01 10:10:00
John   room1  2018-01-01 10:05:00     2018-01-01 10:10:00
Doe    room1  2018-01-01 10:20:00     2018-01-01 10:30:00
John   room2  2018-01-01 11:00:00     2018-01-01 11:05:00
John   room2  2018-01-01 11:08:00     2018-01-01 11:15:00
John   room1  2018-01-01 12:00:00     2018-01-01 12:08:00
John   room1  2018-01-01 12:10:00     2018-01-01 12:20:00
John   room1  2018-01-01 12:25:00     2018-01-01 12:25:00
John   room3  2018-01-01 12:30:00     2018-01-01 12:35:00
John   room3  2018-01-01 12:40:00     2018-01-01 12:50:00

我正在寻找一种方法来查询显示用户留在各个房间,汇总与同一房间相关的数据并计算整体停留时间,如下所示

User  Area    EnterTime               ExitTime              ArregateTime
John  room1   2018-01-01 10:00:00     2018-01-01 10:10:00   00:10:00
John  room2   2018-01-01 11:00:00     2018-01-01 11:05:00   00:15:00
John  room1   2018-01-01 12:00:00     2018-01-01 12:25:00   00:25:00
John  room3   2018-01-01 12:30:00     2018-01-01 12:50:00   00:20:00
Doe   room1   2018-01-01 10:00:00     2018-01-01 10:30:00   00:30:00

查看各种线程我很确定我必须使用滞后和按函数分区,但目前尚不清楚如何。 任何提示? 最好的问候。

1 个答案:

答案 0 :(得分:0)

AggregateTime在预期结果中并不是aggregate。对于每个max_timemin_timeblock之间似乎存在差异,其中每个块都是由具有相同(users, area)的连续行设置的。

with block as(
    select users, area, entertime, exittime,     
         (row_number() over (order by users, entertime) -
          row_number() over (partition by users, area order by entertime)
         ) as grp
    from your_table
    order by 1,2,3
)
select users, area, entertime, exittime, (exittime - entertime) as duration
from (select users, area, grp, min(entertime) as entertime, max(exittime) as exittime
      from block
      group by users, area, grp
    ) t2
order by 5;

我对“Resetting Row number according to record data change”进行了一些更改,以便找到解决方案。