【问题标题】:sort_array order by a different column, Hivesort_array 按不同的列排序,Hive
【发布时间】:2017-04-14 17:04:54
【问题描述】:

我有两列,一列是产品,一列是购买日期。我可以通过应用 sort_array(dates) 函数来订购日期,但我希望能够在购买日期之前对 sort_array(products) 进行排序。 有没有办法在 Hive 中做到这一点?

表名是

ClientID    Product    Date
100    Shampoo    2016-01-02
101    Book    2016-02-04
100    Conditioner    2015-12-31
101    Bookmark    2016-07-10
100    Cream    2016-02-12
101    Book2    2016-01-03

然后,每个客户获得一行:

select
clientID,
COLLECT_LIST(Product) as Prod_List,
sort_array(COLLECT_LIST(date)) as Date_Order
from tablename
group by 1;

作为:

ClientID    Prod_List    Date_Order
100    ["Shampoo","Conditioner","Cream"]    ["2015-12-31","2016-01-02","2016-02-12"]
101    ["Book","Bookmark","Book2"]    ["2016-01-03","2016-02-04","2016-07-10"]

但我想要的是与正确的购买时间顺序相关联的产品顺序。

【问题讨论】:

  • 一定要用sort_array吗?为什么不按产品、日期排序?
  • @inquisitive_mind - 它不保证订单
  • 给出数据样本
  • 啊,是的,第一步是按 clientID 分组,然后将他们曾经购买的所有产品折叠成一个数组(因此每个客户可以是 1 行)。我想确保购买的产品是按时间顺序排列的。 select clientid, COLLECT_LIST(product), sort_array(COLLECT_LIST(date)) from tablename group by 1;
  • @inquisitive_mind 谢谢!但排序方式不会将所有项目折叠成 1 行

标签: sorting hadoop hive


【解决方案1】:

可以只使用内置函数,但它不是一个漂亮的网站:-)

select      clientid
           ,split(regexp_replace(concat_ws(',',sort_array(collect_list(concat_ws(':',cast(date as string),product)))),'[^:]*:([^,]*(,|$))','$1'),',') as prod_list
           ,sort_array(collect_list(date)) as date_order

from        tablename 

group by    clientid
; 

+----------+-----------------------------------+------------------------------------------+
| clientid |             prod_list             |                date_order                |
+----------+-----------------------------------+------------------------------------------+
|      100 | ["Conditioner","Shampoo","Cream"] | ["2015-12-31","2016-01-02","2016-02-12"] |
|      101 | ["Book2","Book","Bookmark"]       | ["2016-01-03","2016-02-04","2016-07-10"] |
+----------+-----------------------------------+------------------------------------------+

【讨论】:

  • 这就像一个魅力!现在订购了超过 400 万条记录!谢谢!
  • Hive SQL中可以按desc顺序对数组进行排序吗?
猜你喜欢
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多