Help us understand the problem. What is going on with this article?

Prestoで配列を行に変換する

More than 1 year has passed since last update.

配列 -> レコード

配列が入っているカラムをそれぞれ別レコードに変換したい

例えばtblテーブルのtime_rangesカラムに以下のような配列が入っているとする。

["16:00~16:30","16:30~17:00","17:00~17:30","17:30~18:00","18:00~18:30","18:30~19:00","19:00~19:30","19:30~20:00","20:00~20:30","20:30~21:00","21:00~21:30"]

クエリ例

SELECT 
  time_range
FROM
  tbl CROSS
JOIN
  UNNEST(time_ranges) AS t(time_range)

実行結果

スクリーンショット 2017-04-18 22.46.01.png

配列の順番も合わせて別々のレコードに変換したい

WITH ORDINALITY句をつけて、配列の順番を格納するカラムをUNNEST後のカラム構造の末尾に追加すればよい。

クエリ例

SELECT 
  time_id,
  time_range
FROM
  tbl CROSS
JOIN
  UNNEST(time_ranges) WITH ORDINALITY AS t(
    time_range,
    time_id
  )

実行結果

スクリーンショット 2017-04-18 22.44.50.png

文字列の配列が入っているカラムをそのまま連結した1つの文字列にしたい

`ARRAY_JOIN' を使えば一発なことに気づいた

SELECT
  ARRAY_JOIN(ARRAY['Hello', ' ', 'World', '!'], '')

以下は不要

REDUCE関数を使って、CONCATをapplyする。

SELECT
 REDUCE(ARRAY['Hello', ' ', 'World', '!'],
        '',
        (s, x) -> CONCAT(s, x),
        s -> s)

参考

Presto Documentation
https://prestodb.io/docs/current/sql/select.html

https://prestodb.io/docs/current/functions/lambda.html#reduce

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした