2016-02-12 34 views
0

我已經表如下包含在int數組user_id說明和follower_ids每行基本:如何指望陣列的Postgres

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

我想造成這樣

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

如何運行一個問題?

謝謝。

+0

你需要計算的追隨者的數量爲每個用戶? –

+0

是的,我需要計算每個用戶的關注者人數。 –

回答

2

可以使用array_length()功能

select user_id 
     ,array_length(follower_ids,1) count 
from bar 
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; 

輸出:

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