Harry Berkley
Harry Berkley

Reputation: 13

Returning values with same id as one row

Apologies if this has been answered but trying to word this question was a nightmare to wrap my head around.

Essentially I have a table

post_id tag_id
15618 6
15618 109
15618 659
27248 245
27248 6
27248 7
27248 6499

and I essentially want a query that returns

post_id tag_id
15618 6, 109, 659
27248 245, 6, 7, 6499

Upvotes: 1

Views: 1581

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269753

I strongly recommend that you use arrays for this purpose:

select post_id, array_agg(tag_id order by tag_id)
from t
group by post_id;

You can use string_agg(tag_id, ', ' order by tag_id) if you really want a string. In general, though, I find that arrays are much more versatile.

Upvotes: 2

Related Questions