0
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】縦持ちのデータをカンマ区切り文字列として1セルに集約(STRING_AGG)

Posted at

やりたいこと

顧客名customerに対して注文商品名itemが縦持ちされているテーブルを想定します。
各顧客の注文商品名をカンマ区切りで1つのセルに格納したいとします。

image.png

結論

STRING_AGG関数を使用します。
文字列とNULLが混ざる場合(例:Eさん)、NULLが無視されます。
NULLだけの場合(例:Fさん)、NULLが返されます。

WITH
  test_table AS (
  /*
    テスト用テーブルの作成
  */
    SELECT 'Aさん' AS customer, 'コーヒー' AS item
    UNION ALL
    SELECT 'Aさん' AS customer, 'チョコレート' AS item
    UNION ALL
    SELECT 'Bさん' AS customer, '紅茶' AS item
    UNION ALL
    SELECT 'Bさん' AS customer, 'クッキー' AS item
    UNION ALL
    SELECT 'Cさん' AS customer, 'コーヒー' AS item
    UNION ALL
    SELECT 'Dさん' AS customer, 'コーヒー' AS item
    UNION ALL
    SELECT 'Dさん' AS customer, 'チョコレート' AS item
    UNION ALL
    SELECT 'Dさん' AS customer, 'クッキー' AS item
    UNION ALL
    SELECT 'Eさん' AS customer, 'コーヒー' AS item
    UNION ALL
    SELECT 'Eさん' AS customer, NULL AS item
    UNION ALL
    SELECT 'さん' AS customer, NULL AS item
  )

SELECT
  customer
  ,STRING_AGG(item) AS items

FROM
  test_table

GROUP BY
  1

BigQuery公式:STRING_AGG関数

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