window 函数字段的别名在 HAVING 和 WHERE 子句中使用时导致 "not found" 错误
Alias of window function field causing a "not found" error when used in HAVING and WHERE clauses
考虑以下 BigQuery 查询:
SELECT
tn.object AS object_alias,
tn.attribute1 AS attribute1_alias,
tn.attribute2 AS attribute2_alias,
tn.score AS score_alias,
ROW_NUMBER() OVER (PARTITION BY attribute1_alias, attribute2_alias ORDER BY score_alias DESC) AS row_num_alias
FROM
[datasetName.tableName] tn
HAVING # also causes error when using WHERE
row_num_alias <= 20
在此查询中,HAVING
子句中对 row_num_alias
字段的引用导致以下错误:Field 'row_num_alias' not found.
替换 [=15= 时出现相同的错误] 带有 WHERE
子句的子句,似乎为 all window 函数抛出此错误。
这是 BigQuery 中的错误吗?还是我的查询有其他错误?
可能相关:
- Mysterious error when combining lead function, second window function and column alias
- https://code.google.com/p/google-bigquery/issues/detail?id=336&q=window%20alias
一种解决方法是将其转换为子查询并将 WHERE
子句移到子查询之外(见下文),但这看起来很麻烦(希望没有必要)。
SELECT
object_alias,
attribute1_alias,
attribute2_alias,
score_alias,
row_num_alias
FROM
(SELECT
tn.object AS object_alias,
tn.attribute1 AS attribute1_alias,
tn.attribute2 AS attribute2_alias,
tn.score AS score_alias,
ROW_NUMBER() OVER (PARTITION BY attribute1_alias, attribute2_alias ORDER BY score_alias DESC) AS row_num_alias
FROM
[datasetName.tableName] tn
)
WHERE
row_num_alias <= 20
列别名在 WHERE
子句中不起作用,即使在 BigQuery 中也是如此。也不能保证它们在 HAVING
子句中起作用,尽管某些数据库确实支持它。 ORDER BY
中可以使用列别名;我认为标准的这种支持是逐步淘汰 reference-by-number.
的一部分
您知道正确的解决方案,即使用子查询。
顺便说一句,没有 GROUP BY
的 HAVING
子句看起来很别扭。这样的构造经常在 MySQL 中使用,但仅用作 work-around -- MySQL 中的子查询比在其他数据库中产生更多的开销,因为优化器没有那么复杂。
考虑以下 BigQuery 查询:
SELECT
tn.object AS object_alias,
tn.attribute1 AS attribute1_alias,
tn.attribute2 AS attribute2_alias,
tn.score AS score_alias,
ROW_NUMBER() OVER (PARTITION BY attribute1_alias, attribute2_alias ORDER BY score_alias DESC) AS row_num_alias
FROM
[datasetName.tableName] tn
HAVING # also causes error when using WHERE
row_num_alias <= 20
在此查询中,HAVING
子句中对 row_num_alias
字段的引用导致以下错误:Field 'row_num_alias' not found.
替换 [=15= 时出现相同的错误] 带有 WHERE
子句的子句,似乎为 all window 函数抛出此错误。
这是 BigQuery 中的错误吗?还是我的查询有其他错误?
可能相关:
- Mysterious error when combining lead function, second window function and column alias
- https://code.google.com/p/google-bigquery/issues/detail?id=336&q=window%20alias
一种解决方法是将其转换为子查询并将 WHERE
子句移到子查询之外(见下文),但这看起来很麻烦(希望没有必要)。
SELECT
object_alias,
attribute1_alias,
attribute2_alias,
score_alias,
row_num_alias
FROM
(SELECT
tn.object AS object_alias,
tn.attribute1 AS attribute1_alias,
tn.attribute2 AS attribute2_alias,
tn.score AS score_alias,
ROW_NUMBER() OVER (PARTITION BY attribute1_alias, attribute2_alias ORDER BY score_alias DESC) AS row_num_alias
FROM
[datasetName.tableName] tn
)
WHERE
row_num_alias <= 20
列别名在 WHERE
子句中不起作用,即使在 BigQuery 中也是如此。也不能保证它们在 HAVING
子句中起作用,尽管某些数据库确实支持它。 ORDER BY
中可以使用列别名;我认为标准的这种支持是逐步淘汰 reference-by-number.
您知道正确的解决方案,即使用子查询。
顺便说一句,没有 GROUP BY
的 HAVING
子句看起来很别扭。这样的构造经常在 MySQL 中使用,但仅用作 work-around -- MySQL 中的子查询比在其他数据库中产生更多的开销,因为优化器没有那么复杂。