在 Hive 和 Presto 中按分组聚合字符串并按顺序排序
Posted
技术标签:
【中文标题】在 Hive 和 Presto 中按分组聚合字符串并按顺序排序【英文标题】:Aggregate strings in group by and ordered in Hive and Presto 【发布时间】:2017-09-21 12:41:24 【问题描述】:我有一个格式如下的表格:
IDX IDY Time Text
idx1 idy1 t1 text1
idx1 idy2 t2 text2
idx1 idy2 t3 text3
idx1 idy1 t4 text4
idx2 idy3 t5 text5
idx2 idy3 t6 text6
idx2 idy1 t7 text7
idx2 idy3 t8 text8
我希望看到的是这样的:
idx1 text1
idx1 text2, text3
idx1 text4
idx2 text5, text6
idx2 text7
idx2 text8
所以在最后阶段,我可以:
text1
text2, text3
text4
==SEPERATOR==
text5, text6
text7
text8
如何在 Hive 或 Presto 中执行此操作?谢谢。
【问题讨论】:
==SEPERATOR==
?
idx2 idy3 t5
重复两次
已修复。分隔符是任何类型的分隔线。它用于分隔 IDX。
在SQL中做这种格式化没有多大意义
【参考方案1】:
蜂巢
这是基本查询,如果您愿意,可以从这里获取
select IDX
,IDY
,min(time) as from_time
,max(time) as to_time
,concat_ws(',',collect_list (Text)) as text
from (select *
,row_number () over
(
partition by IDX
order by Time
) as rn
,row_number () over
(
partition by IDX,IDY
order by Time
) as rn_IDY
from mytable
) t
group by IDX,IDY
,rn - rn_IDY
order by IDX,from_time
+------+------+-----------+---------+-------------+
| idx | idy | from_time | to_time | text |
+------+------+-----------+---------+-------------+
| idx1 | idy1 | t1 | t1 | text1 |
| idx1 | idy2 | t2 | t3 | text2,text3 |
| idx1 | idy1 | t4 | t4 | text4 |
| idx2 | idy3 | t5 | t6 | text5,text6 |
| idx2 | idy1 | t7 | t7 | text7 |
| idx2 | idy3 | t8 | t8 | text8 |
+------+------+-----------+---------+-------------+
Presto
select array_join(array_agg (Text),',') as text
from (select *
,row_number () over
(
partition by IDX
order by Time
) as rn
,row_number () over
(
partition by IDX,IDY
order by Time
) as rn_IDY
from mytable
) t
group by IDX,IDY
,rn - rn_IDY
order by IDX,min(time)
;
+-------------+
| text |
+-------------+
| text1 |
| text2,text3 |
| text4 |
| text5,text6 |
| text7 |
| text8 |
+-------------+
【讨论】:
以上是关于在 Hive 和 Presto 中按分组聚合字符串并按顺序排序的主要内容,如果未能解决你的问题,请参考以下文章