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?

More than 3 years have passed since last update.

BigQueryのUNPIVOT演算子でテーブルを横持ちから縦持ちにする

0
Posted at

はじめに

横持ちテーブルを縦持ちにしてデータを見やすくしたり扱いやすくしたりしたい時がありました。
BigQueryでUNPIVOT演算子を使うと簡単に縦持ちにできたのでその方法を書いてみます。

横持ちテーブルを縦持ちテーブルに

以下のような横持ちテーブルを縦持ちテーブルにしたいと思います。

member address1 address2 address3 tel1 tel2 tel3
太郎 太郎の住所1 太郎の住所2 太郎の住所3 080-0000-1111 080-0000-2222 NULL
次郎 次郎の住所1 次郎の住所2 NULL 080-1111-1111 080-1111-2222 080-1111-3333
SELECT
  member
  ,column_name
  ,value
FROM
  MEMBERS
UNPIVOT (
  value
  FOR column_name
  IN (
  address1
  , address2
  , address3
  , tel1
  , tel2
  , tel3
  )
);

member column_name value
太郎 address1 太郎の住所1
太郎 address2 太郎の住所2
太郎 address3 太郎の住所3
太郎 tel1 080-0000-1111
太郎 tel2 080-0000-2222
次郎 address1 次郎の住所1
次郎 address2 次郎の住所2
次郎 tel1 080-1111-1111
次郎 tel2 080-1111-2222
次郎 tel3 080-1111-3333

カラムの値がNULLの場合は除外されるため、UNPIVOTの後ろに「INCLUDE NULLS」をつけます。

member address1 address2 address3 tel1 tel2 tel3
太郎 太郎の住所1 太郎の住所2 太郎の住所3 080-0000-1111 080-0000-2222 NULL
次郎 次郎の住所1 次郎の住所2 NULL 080-1111-1111 080-1111-2222 080-1111-3333
SELECT
  member
  ,column_name
  ,value
FROM
  MEMBERS
UNPIVOT INCLUDE NULLS (
  value
  FOR column_name
  IN (
  address1
  , address2
  , address3
  , tel1
  , tel2
  , tel3
  )
);

member column_name value
太郎 address1 太郎の住所1
太郎 address2 太郎の住所2
太郎 address3 太郎の住所3
太郎 tel1 080-0000-1111
太郎 tel2 080-0000-2222
太郎 tel3 NULL
次郎 address1 次郎の住所1
次郎 address2 次郎の住所2
次郎 address3 NULL
次郎 tel1 080-1111-1111
次郎 tel2 080-1111-2222
次郎 tel3 080-1111-3333

さいごに

公式ドキュメントにはこの記事で取り扱わなかったオプションがたくさん書かれてあるので
いろいろ試してみたいと思います。

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?