このトピックでは、CROSS JOINステートメントとUNNEST句を使用して、コンマ (,) で区切られた行の値を複数の行に変換する方法について説明します。
配列を複数の行に変換する
列のデータを配列に変換し、その配列を複数の行に変換します。 例:
#### Create a database.
CREATE DATABASE mydb;
USE mydb;
### Create a table.
CREATE TABLE test(
userid INT
,user_name VARCHAR
,product VARCHAR
) distributed by hash(userid);
### Insert two rows of test data into the table.
INSERT INTO test VALUES
(1,'aaa','cat,mat,bat'),(2,'bbb','dog,pog,fog');
#### Convert the product column into multiple rows, save the rows in the col column of the temp_table table, and then query the data of the col column.
SELECT userid, col
FROM (select userid, split(product,',') as numbers_array from test)
CROSS JOIN UNNEST(numbers_array) as temp_table(col);
### Query result:
userid col
1 cat
1 mat
1 bat
2 dog
2 pog
2 fog