简体   繁体   English

用于组合多列的 SQL 查询

[英]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.我正在 AWS Athena 中用 SQL 编写查询,但在某些情况下我无法弄清楚查询。

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.有没有办法为此编写sql查询。 Thanks in advance.提前致谢。

One method is union all :一种方法是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 10
a一种 11 11
b 20 20
b 21 21

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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