【问题标题】:HiveQL - Calculate Time Difference Between Two Rows Based On A ConditionHiveQL - 根据条件计算两行之间的时间差
【发布时间】:2020-10-25 16:27:23
【问题描述】:

我想这样计算每个 ID 的时间差:Time_difference1 是 status=4 - status=2 时的时间戳差,Time_difference2 是 status=3 - status=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

但它不起作用。 OVER PARTITION BY 部分给出错误:不匹配的输入'FROM'期待;第 5 行 pos 0

有人知道如何进行吗?

【问题讨论】:

  • 您的问题相当混乱。您的时间戳看起来根本不像时间戳。您的查询与示例数据没有太大关系。

标签: sql time hive timestamp hiveql


【解决方案1】:

我想这样计算每个 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 2022-08-18
    • 2022-01-08
    • 2020-03-26
    • 2019-06-10
    相关资源
    最近更新 更多