简体   繁体   中英

SQL query to combine multiple columns

I am writing a query in SQL in AWS Athena and there's a situation for which I am not able to figure out the query.

Suppose, I have data in this format. 在此处输入图片说明

And I want my table in this format.

在此处输入图片说明

Is there a way we can write sql query for this. Thanks in advance.

One method is union all :

select name, idaction_url as idaction
from t
union all
select name, idaction_name
from t
union all
select name, idaction_content_interaction
from t;

Not sure if it is better option but you can transform needed fields to array and then unnest it:

WITH dataset AS (
    SELECT *
    FROM (VALUES
        ('a', 10, 11),
        ('b', 20,21)) AS t (user_id, idaction_1, idaction_2))


SELECT user_id, idaction
FROM (
    SELECT user_id, ARRAY[idaction_1, idaction_2] arr
    FROM dataset)
CROSS JOIN UNNEST(arr) as tmp(idaction)
user_id idaction
a 10
a 11
b 20
b 21

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM