【问题标题】:Adding a "calculated column" to BigQuery query without repeating the calculations向 BigQuery 查询添加“计算列”而不重复计算
【发布时间】:2020-07-14 12:51:09
【问题描述】:

我想在新的第三列中重用计算列的值。 例如,此查询有效:

select
  countif(cond1) as A,
  countif(cond2) as B,
  countif(cond1)/countif(cond2) as prct_pass
  From 
  Where
  Group By

但是当我尝试使用 A,B 而不是重复计数时,它不起作用,因为 A 和 B 是 invalid:

select
  countif(cond1) as A,
  countif(cond2) as B,
  A/B as prct_pass
  From 
  Where
  Group By

我能否以某种方式使第二个版本更具可读性? 这第一个效率低吗?

【问题讨论】:

    标签: google-bigquery firebase-analytics


    【解决方案1】:

    你应该像这样构造一个子查询(即双选)

    SELECT A, B, A/B as prct_pass 
    FROM 
    (
    SELECT countif(cond1) as A, 
           countif(cond2) as B 
           FROM <yourtable>
    )
    

    两个查询将处理相同数量的数据。 在子查询中,您将只执行 2 个 countif(),如果该步骤需要很长时间,那么执行 2 而不是 4 确实应该更有效。

    看一个使用 bigquery 公共数据集的示例:

    SELECT 
    countif(homeFinalRuns>3) as A,
    countif(awayFinalRuns>3) as B,
    countif(homeFinalRuns>3)/countif(awayFinalRuns>3) as division 
    FROM `bigquery-public-data.baseball.games_post_wide`  
    

    或

    SELECT A, B, A/B as division FROM 
    (
    SELECT countif(homeFinalRuns>3) as A, 
           countif(awayFinalRuns>3) as B 
           FROM `bigquery-public-data.baseball.games_post_wide`  
    )
    

    我们可以看到,多合一(没有子查询)实际上要快一些。 (我针对不等式的不同值运行了 6 次查询,快 5 次,慢 1 次)

    在任何情况下,效率都取决于计算特定数据集中条件的繁重程度。

    【讨论】:

    • 不错的实验。让人大开眼界
    猜你喜欢
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多