Please note, this is not a duplicate of the questions cited in the comments, as this requires a CTE.
How do you create a recursive Common Table Expression which combines grouped data (like string_agg() or group_concat())?
For example, I have a simple data set like the following:
┌──────┬──────────┐
│ code │ category │
╞══════╪══════════╡
│ 1    │ A        │
├──────┼──────────┤
│ 1    │ B        │
├──────┼──────────┤
│ 2    │ A        │
├──────┼──────────┤
│ 3    │ B        │
├──────┼──────────┤
│ 4    │ B        │
├──────┼──────────┤
│ 4    │ C        │
├──────┼──────────┤
│ 4    │ D        │
├──────┼──────────┤
│ 5    │ B        │
└──────┴──────────┘
I would like to generate a result set which combines the categories by group as follows:
┌──────┬──────────┐
│ code │ category │
╞══════╪══════════╡
│ 1    │ A,B      │
├──────┼──────────┤
│ 2    │ A        │
├──────┼──────────┤
│ 3    │ B        │
├──────┼──────────┤
│ 4    │ B,C,D    │
├──────┼──────────┤
│ 5    │ B        │
└──────┴──────────┘
I think the answer is probably generic, but I am particularly interested in finding a solution for PostgreSQL, SQLite and, and SQL Server.
 
    