0

I have table follow that contain user_id and follower_ids in int array:

id | user_id | follower_ids
---|---------|-------------
1  | 1       | {2,3,4}
2  | 2       | {1}
3  | 3       | {1,2}
4  | 4       | {1}

I want to get result like this

user_id | count
--------| -----
1       | 3
2       | 2
3       | 1
4       | 1

how do i run a query?

Thank you.

2
  • do you need to calculate the number of followers for each user? Commented Feb 12, 2016 at 5:20
  • yes i need to count number of followers for each user. Commented Feb 12, 2016 at 6:50

2 Answers 2

2

You can use array_length() function

select user_id
      ,array_length(follower_ids,1) count
from bar
Sign up to request clarification or add additional context in comments.

Comments

0
WITH t(id,user_id,follower_ids) AS ( VALUES
  (1,1,ARRAY[2,3,4]),
  (2,2,ARRAY[1]),
  (3,3,ARRAY[1,2]),
  (3,4,ARRAY[1])
)
SELECT
  follower AS user_id,
  count(follower) AS follower_count
FROM t,unnest(t.follower_ids) AS follower
GROUP BY 1
ORDER BY 1;

Output:

 user_id | follower_count 
---------+----------------
       1 |              3
       2 |              2
       3 |              1
       4 |              1
(4 rows)

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.