0

Suppose I have the following table in Postgres:

CREATE TABLE movies (
    id serial primary key,
    title text,
    actor_ids bigint[]
)

How can I get the number of movies each actor has starred in? I should be printed like this:

actor_id | count
----------------
53       | 4
92       | 13
132      | 1
1221     | 2

The actor_ids column is an array that contains the ids of the actors starring in the movie.

2
  • Right, deleted the comment. Didn't register the bit about the array. Commented Mar 31, 2021 at 14:50
  • Yeap, it's fine. Thanks for taking the time to read my question. Commented Mar 31, 2021 at 14:55

1 Answer 1

2

You need to first unnest the array, then you can apply a group by and count

select a.actor_id, count(*)
from movies m
  cross join unnest(m.actor_ids) as a(actor_id)
group by a.actor_id
order by a.actor_id;
Sign up to request clarification or add additional context in comments.

1 Comment

This did the job just right, Thanks a lot! I thought it would be something unnest. Have a good one!

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.