【问题标题】:Create Statistics Summary on Selected Columns in BigQuery在 BigQuery 中为选定列创建统计信息摘要
【发布时间】:2021-11-06 09:26:12
【问题描述】:

我正在尝试从几个数字列中总结一些静态属性,例如连续分位数、均值、标准差等,然后将它们包装到行中,并将原始列名作为附加列附加。我知道使用AVGSTDDEV_POPERCENTILE_CONT... 从单个列中获取它们,但没有找到关于同时在多个列上执行它们的文章/食谱。有什么想法吗?

示例输入:

ID Col1 Col2 Col3
1 1.0 2.0 4.0
2 2.0 4.0 8.0
3 3.0 6.0 12.0
4 4.0 8.0 16.0

预期输出:

Col Name Q1 Q2 Q3 Mean Std
Col1 1.75 2.5 3.25 2.5 1.12
Col2 3.5 5.0 6.5 5.0 2.24
Col3 7.0 10.0 13.0 10.0 4.47

或“转置”版本:

Stats Col1 Col2 Col3
Q1 1.75 3.5 7.0
Q2 2.5 5.0 10.0
Q3 3.25 6.5 13.0
Mean 2.5 5.0 10.0
Std 1.12 2.24 4.47

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    考虑下面

    select distinct col, 
      percentile_cont(value, 0.25) over win as q1,
      percentile_cont(value, 0.50) over win as q2,
      percentile_cont(value, 0.75) over win as q3,
      avg(value) over win as avg, 
      stddev_pop(value) over win as std, 
    from your_table
    unpivot (value for col in (col1, col2, col3))
    window win as (partition by col)                 
    

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

    要获得“转置”版本 - 在下面使用

    select * from (
      select * from (
        select distinct col, 
          percentile_cont(value, 0.25) over win as q1,
          percentile_cont(value, 0.50) over win as q2,
          percentile_cont(value, 0.75) over win as q3,
          avg(value) over win as avg, 
          stddev_pop(value) over win as std, 
        from data
        unpivot (value for col in (col1, col2, col3))
        window win as (partition by col)
      ) unpivot (value for stats in (q1, q2, q3, avg, std))
    ) pivot (any_value(value) for col in ('col1', 'col2', 'col3'))
    

    在这种情况下 - 输出是

    【讨论】:

    • 谢谢!很高兴知道这种类型的摘要可以通过UNPIVOTWINDOW 子句实现。
    • 另外,屏幕截图显示我在预期输出中犯了很多错误。他们都修好了! :D
    • 很高兴您注意到这一点 :o)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    相关资源
    最近更新 更多