在不重复计算的情况下向 BigQuery 查询添加 "calculated column"
Adding a "calculated column" to BigQuery query without repeating the calculations
我想在新的第三列中重新使用计算列的值。
例如,此查询有效:
select
countif(cond1) as A,
countif(cond2) as B,
countif(cond1)/countif(cond2) as prct_pass
From
Where
Group By
但是当我尝试使用 A,B 而不是重复 countif 时,它不起作用,因为 A 和 B 是 invalid:
select
countif(cond1) as A,
countif(cond2) as B,
A/B as prct_pass
From
Where
Group By
我能否以某种方式使第二个版本更具可读性?
第一个效率低吗?
您应该构造一个子查询(即双 select),如
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 public 数据集的示例:
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次)
在任何情况下,效率将取决于计算特定数据集中条件的工作量。
我想在新的第三列中重新使用计算列的值。 例如,此查询有效:
select
countif(cond1) as A,
countif(cond2) as B,
countif(cond1)/countif(cond2) as prct_pass
From
Where
Group By
但是当我尝试使用 A,B 而不是重复 countif 时,它不起作用,因为 A 和 B 是 invalid:
select
countif(cond1) as A,
countif(cond2) as B,
A/B as prct_pass
From
Where
Group By
我能否以某种方式使第二个版本更具可读性? 第一个效率低吗?
您应该构造一个子查询(即双 select),如
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 public 数据集的示例:
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次)
在任何情况下,效率将取决于计算特定数据集中条件的工作量。