1

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
  • 1
    Have a look at this post https://stackoverflow.com/questions/15847173/concatenate-multiple-result-rows-of-one-column-into-one-group-by-another-column – avikalb Jul 12 '21 at 00:37
  • Does this answer your question? [Concatenate multiple result rows of one column into one, group by another column](https://stackoverflow.com/questions/15847173/concatenate-multiple-result-rows-of-one-column-into-one-group-by-another-column) – Jahnavi Paliwal Jul 12 '21 at 04:19

1 Answers1

2

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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Arrays work fine. The format of the result isn't an issue. Just couldn't wrap my head around a way to make the result I wanted happen. I even looked at join and such – Harry Berkley Jul 12 '21 at 00:46