【问题标题】:Hive collect_set() but to Remove Consecutive DuplicatesHive collect_set() 但要删除连续重复
【发布时间】:2019-10-22 20:26:13
【问题描述】:

我想在使用 hive 时删除数组中的连续重复项。

collect_list() 保留所有重复项,而 collect_set() 仅保留不同的条目。我有点需要中间地带的东西。

例如,从下表:

id  |  number
==============
fk        4
fk        4
fk        2
4f        1
4f        8
4f        8
h9        7
h9        4
h9        7

我想得到这样的东西:

id | aggregate
===========================
fk   Array<int>(4,2)
4f   Array<int>(1,8)
h9   Array<int>(7,4,7)

【问题讨论】:

  • 问题是数据集中没有确定行顺序的列。是什么让 h9,7 和 h9,4 连续?表未按定义排序。只有 order by 才能保证所需的行顺序。另请阅读:stackoverflow.com/a/47416027/2700344
  • 好点!忘了说这已经按时间戳排序了。
  • 您还有一个时间戳列,对吧?没有这个专栏,问题就无法挽救了

标签: sql arrays list hive hiveql


【解决方案1】:

使用lag()解析函数获取前一个号码并与当前号码进行比较以检查连续号码。

演示:

with your_table as (--replace this subquery with your table
select stack(11, --the number of tuples
'fk',4,'2019-01-01 10:10:10.123',
'fk',4,'2019-01-01 10:10:10.124',
'fk',2,'2019-01-01 10:10:10.125',
'4f',1,'2019-01-01 10:10:10.126',
'4f',8,'2019-01-01 10:10:10.127',
'4f',8,'2019-01-01 10:10:10.128',
'h9',7,'2019-01-01 10:10:10.129',
'h9',4,'2019-01-01 10:10:10.130',
'h9',7,'2019-01-01 10:10:10.131',
'h9',7,'2019-01-01 10:10:10.132',
'h9',7,'2019-01-01 10:10:10.133'
) as (id, number, order_ts)
) --replace this subquery with your table

select id, collect_list(case when number = lag_number then null else number end) as aggregate
  from 
      (select id, number, order_ts,
              lag(number) over (partition by id order by order_ts) lag_number
         from your_table 
       distribute by id sort by order_ts
      )s         
  group by id;

结果:

id  aggregate   
4f  [1,8]   
fk  [4,2]   
h9  [7,4,7] 

【讨论】:

    猜你喜欢
    • 2011-09-20
    • 2018-12-01
    • 1970-01-01
    • 2020-03-30
    • 2013-10-28
    • 2017-09-17
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多