hiveql基于一个条件计算两行之间的时间差

sqougxex  于 2021-04-21  发布在  Hive
关注(0)|答案(1)|浏览(777)

我想计算每个ID的时间差,就像这样:time_difference1是状态=4-状态=2时的时间差,time_difference2是状态=3-状态=2时的差。
我的表格看起来像这样

id  status  timestamp
16  1       12.45.12
16  2       12.45.30
16  3       12.45.55
16  4       12.46.15
11  1       12.45.46
11  2       12.45.55
11  3       12.46.11
11  4       12.46.34
27  1       12.48.01
27  2       12.48.18
27  3       12.48.42
27  4       12.48.52

所以结果应该是这样的。

id  timediff1   timediff2
16  0.00.45     0.00.25
11  0.00.25     0.00.16
27  0.00.41     0.00.24

我已经尝试了一些解决方案,比如

SELECT id,
   status
   timestamp,
   (to_unix_timestamp(case1) - to_unix_timestamp(timestamp)) AS timediff1
FROM (
  SELECT t.*,
         CASE WHEN status=4 THEN timestamp END OVER (PARTITION BY id ORDER BY timestamp ASC) AS case1
  FROM table t 
)
WHERE status = 2

但它不起作用。通过分区的部分给出错误:不匹配的输入'from'期望;第5行位置0
有谁知道该如何进行?

6gpjuf90

6gpjuf901#

我想计算每个ID的时间差,像这样:time_difference1是status=4-status=2时的时间差,time_difference2是status=3-status=2时的时间差。
使用条件聚合。

SELECT id,
       (max(to_unix_timestamp(case when status = 4 then timestamp end)) - 
        max(to_unix_timestamp(case when status = 2 then timestamp end))
       ) AS timediff1,
       (max(to_unix_timestamp(case when status = 3 then timestamp end)) - 
        max(to_unix_timestamp(case when status = 2 then timestamp end)
       ) AS timediff2)
FROM t 
GROUP BY id

相关问题