【问题标题】:BigQuery unnest percentile struct to a table with columnsBigQuery 将百分位结构嵌套到具有列的表中
【发布时间】:2021-10-23 07:14:37
【问题描述】:

我有一张如下所示的表格

id city price
1 Bacelona 300
2 Barcelona 200
3 London 1000
4 London 2000

我想创建一个包含每个城市百分位数的表格 我正在使用以下查询创建一个结构

SELECT AS STRUCT City, APPROX_QUANTILES(CAST(Price as INTEGER), 100) AS quants
  FROM T
  where Price > 0
  group by City

如何将结构展平(取消嵌套)到具有以下列的表中 城市、偏移量、Qant

其中包括源表 T 中所有可用城市的所有百分位数?

感谢您的帮助 谢谢

【问题讨论】:

    标签: google-bigquery unnest


    【解决方案1】:

    一开始我生成你的表with T as ()

    然后使用您的查询获取 QUANTILES(此处仅 10 个以使示例更具可读性)。然后是数据是unnest,并且row_number 每行都有一个索引值。 Pivot 将每个数字放在一列中。从 1 到 100 的数字必须手写。

    With T as (
    Select 1 id,    "Bacelona" city,    300  price UNION ALL 
    select 2,"Barcelona",   200 UNION ALL 
    select 3,"London",  1000 UNION ALL 
    select 4,"London",  2000 
    )
    
    SELECT *
    from(
    SELECT city,quant,row_number() over (partition by city) as r
    from (
    SELECT AS STRUCT City, APPROX_QUANTILES(CAST(Price as INTEGER), 10) AS quants, row_number() over (partition by city) as r
      FROM T
      where Price > 0
      group by City
    ), unnest(quants) as quant
    )
    pivot( min(quant) for r in ( 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) ) 
    

    如果应该命名列名:

    SELECT city,quant,concat("quant",cast(row_number() over (partition by city) as string)) as r
    ...
    pivot( min(quant) for r in ( "quant1","quant2","quant3") ) 
    

    【讨论】:

    • 非常感谢@Samuel。这非常有帮助。您能否告诉我如何使用 lag() 函数将结果表显示为 City、quant、pre-quant,但使用每个城市的数据(如按城市划分,但 lag 函数按顺序排列)。问题是第二个城市的第一个 pre-quant 被第一个城市的最后一个 quant 填充。如何使其为空?
    猜你喜欢
    • 2015-03-25
    • 2020-03-14
    • 1970-01-01
    • 2016-06-21
    • 2023-01-11
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多