2

I've got mytable1 with row_number integer and list_of_ids int[] column

mytable2 with id integer and company text columns

Example entry for mytable1

1 | {633681,1278392,2320888,2200426}
2 | {2443842,2959599,3703823,3330376,915750,941736}

Example entry for mytable2

 633681 | apple
1278392 | charmander
2320888 | apple
2200426 | null
2443842 | batman

I need to feed back values from mytable2 into mytable1. This way the expected output would be

1 | {633681,1278392,2320888,2200426} | 2 apple, 1 charmander, 1 null
2 | {2443842,2959599,3703823,3330376,915750,941736} | 1 batman etc...
1
  • A lateral cross join with unnest, then join and aggregate. Commented Dec 13, 2019 at 15:12

1 Answer 1

2

You need to unnest the lists of ids, join mytable2 using unnested ids and finally aggregate back the data to get a single row for a row_number.

select 
    row_number, 
    list_of_ids, 
    string_agg(format('%s %s', count, company), ', ' order by count desc, company)
from (
    select 
        row_number, 
        list_of_ids, 
        coalesce(company, '<null>') as company, 
        count(*)
    from (
        select row_number, list_of_ids, unnest(list_of_ids) as id
        from mytable1
        ) t1
    join mytable2 t2 using(id)
    group by 1, 2, 3
    ) s
group by 1, 2

Db<>fiddle.

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

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.