0

Suppose I have a table like the following

user score_1 score_2 score_3
1 100 80 100
1 80 null 80
2 95 90 65

I would like to aggregate the 3 scores columns into an array. The result will look like (the order does not matter)

user scores
1 [100,80,100,80,null,80]
2 [95,90,65]

I know I can take union of (user, score1), (user, score2) and (user,score3) and then do array_agg on top of that. I am wondering if there is a more efficient way.

2
  • you cannot have null as an element of array in final output! so you should adjust your expectations! Commented Sep 29, 2022 at 5:02
  • You can array_agg first and then array_concat, but you need to decide how you want to handle nulls Commented Sep 29, 2022 at 5:09

2 Answers 2

1

If for some reason preserving null is a must for you - you can use below trick - but note - the output is not an array and rather string

select user, 
  translate(format('%t', array_agg(struct(score_1, score_2, score_3))), '()', '') scores
from your_table
group by user

or even simpler

select user, 
  format('%t', array_concat_agg([score_1,score_2,score_3])) scores
from your_table
group by user

with same output for both above

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Consider below

select user, array_agg(score) scores
from your_table
unpivot (score for col in (score_1, score_2, score_3))
group by user          

if applied to sample data in your question - output is

enter image description here

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.