【问题标题】:Hive: How to concat one column by order after group by?Hive:如何在分组后按顺序连接一列?
【发布时间】:2021-09-24 21:25:13
【问题描述】:

数据集如下所示:

id result rank
001 pass 2
002 fail 3
001 fail 1
002 pass 1

我想要做的:按 id 对数据集进行分组,并按照排名列的升序连接结果。

id results
001 fail-pass
002 pass-fail

由于涉及到其他列的顺序,concat_ws('-',collect_set(result))函数无法实现我的想法。

是否有任何内置函数可以帮助我实现这一点,或者编写 UDF 似乎是唯一的解决方案?

【问题讨论】:

    标签: sql arrays hive concatenation hiveql


    【解决方案1】:

    有人在 azure 上有 databricks sql 的解决方案吗?

    databricks 中的 collect_set 函数似乎把所有排序的东西都弄乱了:(

    with demo_dataset as ( --Use your table instead of this CTE
    select stack(4,
    '001' , 'pass', 2,
    '002' , 'fail', 3,
    '001' , 'fail', 1,
    '002' , 'pass', 1
    ) as (id,result,rank)
    )
    
    select id, concat_ws('-', collect_set(result))
    from
    (
    select t.* 
      from demo_dataset t
    distribute by id   --Distribute by grouping column
    sort by id, rank ASC  --Sort in required order
    ) s
    group by id
    

    返回:

    但是子查询没问题:

    【讨论】:

      【解决方案2】:

      在collect_set之前的子查询中,按id分布,按id排序,排序。数据集将在 reducer 之间按 id 分布,并在聚合之前按等级排序。见代码中的 cmets。

      演示:

      with demo_dataset as ( --Use your table instead of this CTE
      select stack(4,
      '001' , 'pass', 2,
      '002' , 'fail', 3,
      '001' , 'fail', 1,
      '002' , 'pass', 1
      ) as (id,result,rank)
      )
      
      select id, concat_ws('-',collect_set(result))
      from
      (
      select t.* 
        from demo_dataset t
      distribute by id   --Distribute by grouping column
      sort by id, rank   --Sort in required order
      ) s
      group by id
      

      结果:

      id  results
      001 fail-pass
      002 pass-fail
      

      现在,如果您更改 SORT:sort by id, rank desc,您将获得不同排序的结果

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 2017-09-21
        • 2023-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-17
        相关资源
        最近更新 更多