【问题标题】:how to find the activity idle time of a person using sql如何使用sql查找一个人的活动空闲时间
【发布时间】:2020-02-23 11:16:33
【问题描述】:

worker 表跟踪工人在给定一天所进行的所有工作。您如何查询该表以找出他空闲时没有任何工作的时间和时间戳。

因此,当他拿起他的第一件作品,然后他又拿起另一件,然后又放下这两件作品时,桌子上可能会有记录。过了一会儿,他又拿起了一些,又被记录在了表格中。

那么,当他没有任何工作时,你如何找到数据

表:worker

  worker_id | task_id |      start_ts       |       end_ts        
 -----------|---------|---------------------|--------------------- 
          1 |       1 | 2019-27-10 03:14:07 | 2019-27-10 03:20:07 
          1 |       2 | 2019-27-10 03:19:07 | 2019-27-10 03:25:07 
          1 |       3 | 2019-27-10 03:18:07 | 2019-27-10 05:20:07 
          2 |       1 | 2019-27-10 06:14:07 | 2019-27-10 06:20:07 
          3 |       2 | 2019-27-10 06:19:07 | 2019-27-10 06:25:07 
          4 |       3 | 2019-27-10 06:18:07 | 2019-27-10 07:20:07 

【问题讨论】:

  • 工人真的可以同时处理多项任务吗?根据您的样本数据,您想要的输出到底是什么?
  • 您好,感谢您的回复。这是我这里给出的测试数据。请不要进入它的语义。但我正在寻找相同的逻辑

标签: sql postgresql time-series gaps-and-islands


【解决方案1】:

您可以将数据拆分为单独的时间戳。然后将+1 分配给开始时间,将-1 分配给结束时间(加一秒)。该值的累积总和告诉您某人在该时间开始了多少任务。

所以最后一步是过滤值为0的地方:

with t as (
      select worker_id, start_ts as ts, 1 as inc
      from work
      union all
      select worker_id, end_ts + interval '1 second' as ts, -1 as inc
      from work
     ),
     t2 as (
      select t.worker, t.ts,
             sum(sum(t.inc)) over (partition by t.worker_id) as num_tasks,
             lead(t.ts) over (partition by t.worker, t.ts) as next_ts
      from t
      group by t.worker, t.ts
     )
select t2.*
from t2
where num_tasks = 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    相关资源
    最近更新 更多