如何编写HQL / SQL解决以下问题

时间:2019-04-09 16:12:08

标签: sql hive hql hiveql

我正在尝试编写以下代码以实现输出?

输入:

+----------------------+
|         dttm         |
+----------------------+
| 2014-11-18 16:23:01  |
| 2014-11-18 16:23:02  |
| 2014-11-18 16:26:14  |
| 2014-11-18 16:26:15  |
| 2014-11-18 16:26:16  |
| 2014-11-18 17:43:02  |
| 2014-11-18 17:43:03  |
| 2018-12-17 23:59:59  |
| 2018-12-18 00:00:00  |
| 2019-01-17 00:00:00  |
| 2019-01-17 00:00:01  |
+----------------------+

输出:

+----------------------+
|         dttm         |
+----------------------+
| 2014-11-18 16:23:01  |
| 2014-11-18 16:23:02  |
| 2014-11-18 16:26:14  |
| 2014-11-18 16:26:15  |
| 2014-11-18 16:26:16  |
| 2014-11-18 16:26:16  |
| 2014-11-18 17:43:02  |
| 2014-11-18 17:43:03  |
| 2018-12-17 23:59:59  |
| 2018-12-18 00:00:00  |
| 2019-01-17 00:00:00  |
| 2019-01-17 00:00:01  |
+----------------------+

实施逻辑:第1行和第2行的差应为1秒,第3行和第4行的差应为1秒,依此类推。

如果不是这种情况,请复制该订单项。

1 个答案:

答案 0 :(得分:0)

尝试



select a.dttm from (
select   t1.rn, t1.dttm, case when  (unix_timestamp(t2.dttm) - unix_timestamp(t1.dttm) )  = 1 then '1' when  (unix_timestamp(t2.dttm) - unix_timestamp(t1.dttm)) is null then '1' else '1,2' end as split_rec
from (select dttm, row_number () over () as rn from tmstmp) t1 left outer join
(select dttm, row_number () over () as rn from tmstmp) t2
on t1.rn = t2.rn-1 and pmod(t2.rn,2) =0) a
lateral view explode(split(a.split_rec , ',')) temp as td1
;



Output is :

+-----------+------------------------+--+
| temp.td1  |         a.dttm         |
+-----------+------------------------+--+
| 1         | 2014-11-18 16:23:01.0  |
| 1         | 2014-11-18 16:23:02.0  |
| 1         | 2019-01-17 00:00:00.0  |
| 1         | 2019-01-17 00:00:01.0  |
| 1         | 2014-11-18 16:26:14.0  |
| 1         | 2014-11-18 16:26:15.0  |
| 1         | 2014-11-18 16:26:16.0  |
| 2         | 2014-11-18 16:26:16.0  |
| 1         | 2014-11-18 16:26:16.0  |
| 1         | 2014-11-18 17:43:02.0  |
| 1         | 2014-11-18 17:43:03.0  |
| 1         | 2018-12-17 23:59:59.0  |
| 1         | 2018-12-18 00:00:00.0  |
+-----------+------------------------+--+