Skip to content
Advertisement

Select top 3 by element in JSON arrays

The source data is

The output is

I need to filter score>0, and then select each user_id’s top3 video_interest in descending order of score

Advertisement

Answer

Explode JSON array, extract score, calculate max score per user (if necessary to order final output by score desc) and row_number by score to filter top 3, collect array again and concatenate it to STRING if necessary. See comments in the code. I added sorting arrays and the whole output, because it was initially not clear what exactly should be sorted: arrays or final output, remove max_score sorting if you do not need it.

Demo:

Result:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement