如何在 BigQuery 的标准 SQL 中编写 LEFT JOIN?

How to write a LEFT JOIN in BigQuery's Standard SQL?

我们有一个在 BigQuery 的 Legacy SQL 中有效的查询。我们如何用 Standard 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 Standard SQL documentation and also see just - 但到目前为止,我们还不清楚需要进行哪些关键更改。

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 中工作?

您的错误消息表明 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;

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

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 

以上为测试用

您应该 运行 在 "production" 中的查询是

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

以防万一,如果出于某种原因你必须加入,请使用以下 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