array_agg在多列上由一列组成

时间:2014-05-17 04:07:14

标签: sql ruby-on-rails postgresql activerecord

我目前有一个像这样的示例标记表:

id | tag    | user_id | video_id
 1 | cake   |       1 |        1
 2 | cookie |       1 |        2
 3 | crab   |       2 |        2
 4 | carrot |       2 |        2

我想通过video_id将最近的10-20行分组,其他列作为数组:

video_id 1, has tag "cake", user_id 1
video_id 2, has tags "cookie", "cake", "crab", by user_id 1, user_id 2

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效

SELECT video_id, array_agg(tag) as tags, array_agg(user_id) as user_ids
FROM tags
ORDER BY id
GROUP BY video_id
LIMIT 10