I have data of the form
id | col1 | col2 | col3 | col4 | col5 | col6 |
----------------------------------------------
1 | a | b | c | d | e | f |
2 | a | b | c | d | e | f |
3 | a | b | c | d | e | f |
that I'm trying to get into the form
id | key | value |
------------------
1 | col1| a
1 | col2| b
1 | col3| c
1 | col4| d
1 | col5| e
1 | col6| f
2 | col1| a
2 | col2| b
2 | col3| c
2 | col4| d
2 | col5| e
2 | col6| f
3 | col1| a
3 | col2| b
3 | col3| c
3 | col4| d
3 | col5| e
3 | col6| f
and I can't for the life of me figure out how to go about doing it. I can accomplish the opposite and turn a map into a single row based on a key via doing something like the follows, but I'm not sure how to go from a single row to many rows based on the columns.
SELECT
id,
key['a'] AS col1,
key['b'] AS col2
FROM (
SELECT id, map_agg(key, value) key
FROM table_a
GROUP BY id
) temp
Is this something that is possible in presto?
I don't have Presto/Athena onhand to test this, but I think the approach is:
select t.id, kv[1] as key, kv[2] as value
from (select t.*,
array[row('col1', col1),
row('col2', col2),
row('col3', col3),
row('col4', col4),
row('col5', col5),
row('col6', col6)
] as kv_ar
from t
) t cross join
unnest(kv_ar) kv
You can zip arrays & unnest them using cross join unnest
. so, construct a zipped array using column names & column values and then use unnest.
with test (id,col1,col2,col3,col4,col5,col6) AS (
values
(1,'a','b','c','d','e','f'),
(2,'a','b','c','d','e','f'),
(3,'a','b','c','d','e','f')
)
select id, k, v
from test
cross join unnest(
array['col1', 'col2', 'col3', 'col4','col5', 'col6']
, array[col1, col2, col3, col4, col5, col6]
) as x(k, v)
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.