【问题标题】:BigQuery: how to calculate the frequency of numbers in a tableBigQuery:如何计算表格中数字的频率
【发布时间】:2021-12-30 10:32:54
【问题描述】:

我需要计算一个数字在一个表格的 4 列中出现了多少次。

我用过 COUNT(CASE WHEN column_1 = 1 THEN 1 END) 它有效,但仅适用于 1 列和 1 个数字。

是否可以一次添加所有column_N?

如果我需要检查很多数字(从 1 到 90),我该怎么办?

谢谢

【问题讨论】:

    标签: count google-bigquery


    【解决方案1】:

    为了简化对所有列的操作,一次尝试创建一个数组。 请参阅下面的一些示例数据。

    with sample_data as (
        select 1 as id, 1 as col_1, 2 as col_2, 3 as col_3, 4 as col_4 union all 
        select 2, 1, 1, 5, 6 union all 
        select 3, 1, 7, 8, 1
    )
    
    select id
        , target
        , count(target) frequency
    from sample_data
    , UNNEST([col_1 , col_2, col_3, col_4 ]) target
    group by id, target
    
    

    如果列中有不需要的数字,例如,如果您要查找 1-90,但该集合还包含 91+,您将应用 where 子句来过滤掉您不需要的元素。

    作为此方法的替代方法,您可以尝试取消透视您要计数的列,但我认为这更简单。

    【讨论】:

      【解决方案2】:

      考虑下面的方法 - 它处理 your_table 中的所有列,除了 id 列(假设你有这样的)。您可以根据需要添加要排除在除列表中的任意数量的列。

      select id, 
        ( select count(*)
          from unnest(`bqutil.fn.json_extract_values`(to_json_string((
            select as struct * except(id) from unnest([t])
          )))) value
          where value = '1'
        ) as frequency
      from your_table t        
      

      注意:您希望,而不是排除列 - 您可以明确列出要参与搜索的列

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-30
        • 1970-01-01
        • 2022-10-04
        • 2019-07-09
        • 1970-01-01
        • 2017-02-25
        • 1970-01-01
        相关资源
        最近更新 更多