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?

More than 3 years have passed since last update.

JSON_EXTRACT_ARRAY

Posted at

JSON_EXTRACT_ARRAY

便利なやつが現れた

例1

SELECT
  JSON_EXTRACT_ARRAY("[{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]")
f0_
1 {"a":1,"b":2}
{"a":3,"b":4}

ざっくりいうと、JSONの中の配列を扱えるようになった。
ただ、これだけだとイマイチぱっとしない。

例2

WITH data AS (
  SELECT 
    *
  FROM
    UNNEST([
        STRUCT(1 AS user_id, "[{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]" AS json_data),
        (2, "[{'a': 5, 'b': 6}, {'a': 7, 'b': 8}, {'a': 9, 'b': 10}]")
    ])
)

SELECT
  *
FROM
  data
user_id json_data
1 1 [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]
2 2 [{'a': 5, 'b': 6}, {'a': 7, 'b': 8}, {'a': 9, 'b': 10}]

こんなデータがあったとして、それぞれのjson_dataのbの値を抜き出したい場合にこういった書き方ができる

SELECT
  user_id,
  JSON_EXTRACT(ele, '$.b') AS b_value
FROM
  data,
  UNNEST(JSON_EXTRACT_ARRAY(json_data)) AS ele
user_id b_value
1 1 2
2 1 4
3 2 6
4 2 8
5 2 10

こんな感じでJSON_EXTRACT_ARRAYとUNNESTとJSON_EXTRACT(JSON_EXTRACT_SCALAR)を使うことで恐らくどんな形のJSONデータであろうが中身を引っ張ってこれるようになった。

応用次第でいろんな事ができる(気がする)

SELECT
  SUM(CAST(JSON_EXTRACT(ele, '$.a') AS INT64)) AS a_sum,
  SUM(CAST(JSON_EXTRACT(ele, '$.b') AS INT64)) AS b_sum
FROM
  data,
  UNNEST(JSON_EXTRACT_ARRAY(json_data)) AS ele
a_sum b_sum
1 25 30
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?