3

我们有一个适用于 BigQuery 的旧版 SQL 的查询。我们如何用标准 SQL 编写它以使其工作?

SELECT Hour, Average, L.Key AS Key FROM
(SELECT 1 AS Key, * 
FROM test.table_L AS L)
LEFT JOIN 
(SELECT 1 AS Key, Avg(Total) AS Average 
FROM test.table_R) AS R 
ON L.Key = R.Key ORDER BY Hour ASC

目前它给出的错误是:

Equality is not defined for arguments of type ARRAY<INT64> at [4:74]

BigQuery 有两种查询模式:旧版 SQL 和标准 SQL。我们查看了BigQuery 标准 SQL 文档,也只看到了一个关于 BigQuery 中标准 SQL 连接的 SO 答案——但到目前为止,我们还不清楚可能需要进行哪些关键更改。

Table_L 看起来像这样:

Row    Hour
 1      A
 2      B
 3      C

Table_R 看起来像这样:

Row    Value
 1      10
 2      20
 3      30

期望的结果:

Row  Hour  Average(OfR)  Key
 1     A      20          1
 2     B      20          1 
 3     C      20          1

我们如何重写这个 BigQuery Legacy SQL 查询以在标准 SQL 中工作?

4

2 回答 2

2

根据您最近更新的问题和评论 - 请在下面尝试

WITH Table_L AS (
SELECT 1 AS Row, 'A' AS Hour UNION ALL
SELECT 2 AS Row, 'B' AS Hour UNION ALL
SELECT 3 AS Row, 'C' AS Hour 
),
Table_R AS (
SELECT 1 AS Row, 10 AS Value UNION ALL
SELECT 2 AS Row, 20 AS Value UNION ALL
SELECT 3 AS Row, 30 AS Value 
)
SELECT 
  Row, 
  Hour, 
  (SELECT AVG(Value) FROM Table_R) AS AverageOfR,
  1 AS Key
FROM Table_L 

以上用于测试

您应该在“生产”中运行的查询是

SELECT 
  Row, 
  Hour, 
  (SELECT AVG(Value) FROM Table_R) AS AverageOfR,
  1 AS Key
FROM Table_L 

如果由于某种原因您必须加入 JOIN,请使用以下 CROSS JOIN 版本

SELECT 
  Row, 
  Hour, 
  AverageOfR,
  1 AS Key
FROM Table_L
CROSS JOIN ((SELECT AVG(Value) AS AverageOfR FROM Table_R))

或低于涉及 Key 字段的 LEFT JOIN 版本(以防 Key 对您的逻辑真的很重要 - 我觉得这是真的)

SELECT 
  Row, 
  Hour, 
  AverageOfR,
  L.Key AS Key
FROM (SELECT 1 AS Key, Row, Hour FROM Table_L) AS L
LEFT JOIN ((SELECT 1 AS Key, AVG(Value) AS AverageOfR FROM Table_R)) AS R
ON L.Key = R.Key
于 2016-12-26T18:51:05.547 回答
2

您的错误消息表明这key不是table_L. 如果不是,则不要将其包含在查询中。

看起来您只是想要来自 的总数的平均值table_R。您可以这样处理:

SELECT l.*, r.average
FROM test.table_L as l CROSS JOIN
     (SELECT Avg(Total) as average 
      FROM test.table_R
     ) R 
ORDER BY l.hour ASC;
于 2016-12-26T13:16:21.453 回答