【问题标题】:In BigQuery, shuffle values in one column based on sequential ordering of another column在 BigQuery 中,根据另一列的顺序排列一列中的值
【发布时间】:2022-11-16 06:17:37
【问题描述】:
select 't1' as team, 'tom' as name, 1 as value, 1 as rk union all
select 't1' as team, 'joe' as name, 5 as value, 2 as rk union all
select 't1' as team, 'sal' as name, 4 as value, 3 as rk union all
select 't1' as team, 'chi' as name, 9 as value, 4 as rk union all
select 't1' as team, 'nik' as name, 7 as value, 5 as rk union all
select 't1' as team, 'bil' as name, 6 as value, 6 

我们不希望执行普通的 order by 操作,而是希望根据 rk 列中的值对 value 列中的值进行混洗。 rk 最低的行获得最低值。尽管 team 列中只有 1 个唯一值,但在我们的完整数据集中,我们希望按 team 进行分区。此示例数据的目标输出将是:

select 't1' as team, 'tom' as name, 1 as value, 1 as rk union all
select 't1' as team, 'joe' as name, 4 as value, 2 as rk union all
select 't1' as team, 'sal' as name, 5 as value, 3 as rk union all
select 't1' as team, 'chi' as name, 6 as value, 4 as rk union all
select 't1' as team, 'nik' as name, 7 as value, 5 as rk union all
select 't1' as team, 'bil' as name, 9 as value, 6 

... value 中的值现在与 rk 列一起升序。我们可以安全地假设在valuerk 列中的每个team 分区内不会有重复值。我们试过这样使用窗口函数:

select 
  *
  ,any_value(value) over(partition by team order by rk) as newValue
from t1 

但这并没有像我们希望的那样对列进行排序/根本没有。

【问题讨论】:

    标签: google-bigquery


    【解决方案1】:

    考虑以下

    select t.* replace(arr[offset(rk - 1)] as value)
    from your_table t
    join (
      select team, array_agg(value order by value) arr
      from your_table
      group by team
    )
    using(team)       
    

    如果应用于您问题中的样本数据 - 输出是

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2022-01-03
      • 2020-02-08
      • 1970-01-01
      相关资源
      最近更新 更多