9
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ZOZOテクノロジーズAdvent Calendar 2018

Day 2

BigQueryで2つの配列をzipする方法

Last updated at Posted at 2018-12-02

こんな感じに非正規化されてデータが格納されているテーブルがあったとします。

fruit_en furuits_ja
["apple", "pear", "mandarin"] ["林檎", "梨", "蜜柑"]

このテーブルを以下のように変換するにはどうしたら、よいでしょうか?

fruit_en furuits_ja
"apple" "林檎"
"pear" "梨"
"mandarin" "蜜柑"

失敗例: , でJOINする

とりあえずのカンで以下のクエリを書きましたが、失敗しました。

with data as (
  select ["apple", "pear", "mandarin"] as fruit_en, ["林檎", "梨", "蜜柑"] as fruit_ja
)
select fruit_en, fruit_ja from data, unnest(data.fruit_en) as fruit_en, unnest(data.fruit_ja) as fruit_ja

結果

fruit_en fruit_ja
apple 林檎
apple
apple 蜜柑
pear 林檎
pear
pear 蜜柑
mandarin 林檎
mandarin
mandarin 蜜柑

これは , によるJOINがCROSS JOINなための挙動です。

正解

with offset句を使うことで、配列のINDEXを出力し、その情報を使ってJOINすることによって配列のzipを行います。

select fruit_en, fruit_ja from 
  (select fruit_en , offset from data, unnest(data.fruit_en) as fruit_en with offset as offset) join
  (select fruit_ja , offset from data, unnest(data.fruit_ja) as fruit_ja with offset as offset)
  using(offset)
9
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?