I have a table named user_activity.
user_id | book_id | event_type_id |
---|---|---|
1 | 1 | 1 |
1 | 1 | 1 |
1 | 1 | 1 |
1 | 2 | 1 |
1 | 2 | 1 |
1 | 2 | 1 |
1 | 3 | 1 |
event_type_id represents "User has viewed the book".
I want to write a Postgresql query to fetch book ids viewed more than twice by the user as below –
user id | viewed book ids |
---|---|
1 | 1,2 |
2
Answers
You could try the following query:
First you select all the rows where the "User has viewed the book" and then you group them by
user_id
using the group functionSTRING_AGG()
and filter the "groups" that have more than two rows.That should do it.
You have to
group by
twice – byuser_id, book_id
to extract the user-book pairs that qualify (the internal subquery) and then byuser_id
over the result.DB-fiddle
Unrelated, but what is
viewed_book_ids
going to be used for? Maybe it will be more useful as an array (usearray_agg
instead ofstring_agg
) or a JSONB array (usejsonb_agg
) rather than a comma-separated list text.