使用UNNEST()加入包含重复字段的表

时间:2017-07-26 21:20:16

标签: sql join google-bigquery unnest standard-sql

我正在尝试使用BigQuery中的标准SQL连接两个表,一个带有重复字段。使用旧版SQL我提出了这个查询

旧版SQL

SELECT
  b.*,
  t.field1,
  t.field2
FROM
  FLATTEN([table1],repeated_field) AS b
LEFT JOIN
  [table2] AS t
ON
  b.Row = t.RowLabel
  b.seat = t.SeatLabel

重复的字段是seat。我尝试使用unnest()并查看migration guide,但我自己无法提出查询。感谢谢谢。

1 个答案:

答案 0 :(得分:3)

下面是BigQuery Standard SQL

   
#standardSQL
SELECT   
  b.*,
  t.field1,
  t.field2
FROM `table1` AS b, UNNEST(Seats) AS Seat
JOIN `table2` AS t
ON b.Row = t.RowLabel
AND Seat = t.SeatLabel  

您可以使用虚拟数据进行测试,如下所示

#standardSQL
WITH `table1` AS (
  SELECT '1' AS Row, ['a', 'b', 'c'] AS Seats
),
`table2` AS (
  SELECT '1' AS RowLabel, 'b' AS SeatLabel, 111 AS field1, 222 AS field2 UNION ALL
  SELECT '1' AS RowLabel, 'a' AS SeatLabel, 111 AS field1, 222 AS field2 UNION ALL
  SELECT '1' AS RowLabel, 'd' AS SeatLabel, 111 AS field1, 222 AS field2
)
SELECT   
  b.*,
  t.field1,
  t.field2
FROM `table1` AS b, UNNEST(Seats) AS Seat
JOIN `table2` AS t
ON b.Row = t.RowLabel
AND Seat = t.SeatLabel