2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

BigQueryでよく使っている関数

Posted at

はじめに

オペレーション部署からデータ抽出依頼を受けることが多くあります。
様々な要望を受けますが、「指定のカラムを1つにまとめて抽出してほしい」という要望も多くあります。
その際、依頼者の要望とマッチする出し方が可能な関数で、よく使っている書き方を2つ紹介します。

CONCAT

よくある要望:指定のカラムn個を1まとめにして抽出してほしい
(例)column1:AAA
   column2:BBB
   column3:CCC

   結果:AAABBBCCC

sample_CONCAT
select
    CONCAT(CAST(column1 AS STRING), CAST(column2 AS STRING), CAST(column3 AS STRING)) as result
from
    `bigquery-data.sample`
group by result

STRING_AGG

よくある要望:指定のPKに対して紐づくデータが、別テーブルで複数レコード存在する場合、登録順に「/」区切りで1まとめにして抽出してほしい
(例)B.column:AAA  B.registered_at:2025/11/01
   B.column:BBB  B.registered_at:2025/11/10
   B.column:CCC  B.registered_at:2025/11/05

   結果:AAA/CCC/BBB

sample_STRING_AGG
select
    A.id
    ,STRING_AGG(IFNULL(B.column,''),'/' ORDER BY B.registered_at) as result
from
    `bigquery-data.sample_main` A #指定のPK(A.id)を管理しているテーブル
    join `bigquery-data.sample_relation` B on A.id = B.id #A.id(PK)に紐づくデータが複数存在しているテーブル
group by A.id

おわりに

よく使っている関数の使い方を紹介しました。
「こんな感じでselectしたい」などChatGPTに聞きながら書き方を模索していて、数か月後により良い書き方に出会うこともまだまだあります。
実はその瞬間が楽しくもあり、もっと知見を増やしていきたいと改めて思うタイミングでもあります。
今後も新しく得た書き方は記載の内容の更新ができればと思います。
(もし書き方が違っているなどあったらこっそりコメントで教えてもらえるとありがたいです)(小声)

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?