首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Postgresql按循环项目分组

问Postgresql按循环项目分组
EN

Stack Overflow用户
提问于 2018-02-19 05:38:48
回答 1查看 65关注 0票数 0

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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,但不清楚是如何使用的。有什么提示吗?诚挚的问候。

EN

回答 1

Stack Overflow用户

发布于 2018-02-19 05:57:26

在您预期的结果中,AggregateTime并不是一个真正的aggregate。对于每个块来说,max_time和min_time似乎是不同的,因为每个块都是具有相同(users, area)的一组连续行。

代码语言:javascript
复制
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‘做了一些修改以得到解决方案。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48856873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档