我正在使用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看看不同的线程,我很确定我必须使用lag和partition by functions,但不清楚是如何使用的。有什么提示吗?诚挚的问候。
发布于 2018-02-19 05:57:26
在您预期的结果中,AggregateTime并不是一个真正的aggregate。对于每个块来说,max_time和min_time似乎是不同的,因为每个块都是具有相同(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‘做了一些修改以得到解决方案。
https://stackoverflow.com/questions/48856873
复制相似问题