trans_array
The trans_array function is a UDTF that converts one row of data into multiple rows, transforming arrays stored in columns with a fixed delimiter format into multiple rows.
Usage Restrictions
- All key columns must be placed in front, while the columns to be transposed must be placed at the back.
- Only one UDTF is allowed in a single SELECT statement, and no other columns can appear.
- Cannot be used with GROUP BY, CLUSTER BY, DISTRIBUTE BY, or SORT BY.
Syntax
trans_array(num_keys, separator, key1, ..., col1, col2, ...) as (key1, ..., col1, col2, ...)
Parameters
| Parameter | Mandatory | Type | Description |
|---|---|---|---|
| num_keys | Yes | BIGINT | A BIGINT type constant, value must be >= 0. Specifies the number of columns used as keys for transposition when converting to multiple rows. |
| separator | Yes | STRING | A STRING type constant used as the delimiter to split a string into multiple elements. An error is returned if empty. |
| keys | Yes | STRING | The columns used as keys during transposition. The number is specified by num_keys. If num_keys specifies all columns as keys (i.e., num_keys equals the total number of columns), only one row is returned. |
| cols | Yes | STRING | The arrays to be converted into rows. All columns after the keys are treated as arrays to be transposed and must be of STRING type. |
Return Values
The data type of the parameter.
- Returns the transposed rows, with new column names specified by the AS clause.
- The data type of key columns remains unchanged, while all other columns are of STRING type.
- The number of split rows is determined by the array with the most elements. Insufficient elements are filled with NULL.
Example Code
To facilitate understanding of the function's usage, source data is provided along with function-related examples. Create the salary table and add data with the following example command:
CREATE EXTERNAL TABLE salary ( dept_id STRING, -- <department> user_id STRING, -- <employee> sal STRING -- <salary> ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' stored as textfile;
Add data as follows:
d1,user1/user4,1000/6000 d1,user2/user5,2000/7000 d1,user3/user6,3000 d2,user4/user7,4000 d2,user5/user8,5000/8000
Execute SQL (When using a slash (/) in SQL statements, the platform console automatically handles escaping, but when calling via API, you need to manually escape it. Otherwise, a parsing failure error will occur.)
select trans_array(1, "/", dept_id, user_id, sal) as (dept_id, user_id, sal) from salary;
Result:
d1,user1,1000/6000 d1,user4,1000/6000 d1,user2,2000/7000 d1,user5,2000/7000 d1,user3,3000 d1,user6,3000 d2,user4,4000 d2,user7,4000 d2,user5,5000/6000 d2,user8,5000/6000
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot