How Convert Rows to Map in Presto?

Consider SQL statement:

SELECT key, value
FROM (
  SELECT key, value, row_number() OVER (PARTITION BY key ORDER BY length(value) DESC) AS rn
  FROM my_table
)
WHERE rn <= 5;

This produces:

key value
A   1
A   2
B   10

How to make this like:

key values
A   [1;2;3;4;5]
B   [10;20;30;40;50]

Sql engine is presto. Any Ideas?

3

1 Answer

map_agg is the solution:

SELECT key, map_agg(key, value)
FROM (
  SELECT key, value, row_number() OVER (PARTITION BY key ORDER BY length(value) DESC) AS rn
  FROM my_table
)
WHERE rn <= 5 group by key;

Many thanks, @Shantanu Kher for the quickest reply!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest