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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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.