'Select Query with multiple results
I would like to display multiple results in a single line separated by a comma.
Please use this SQL Statement for the sample data set:
DECLARE @TBL_EXAMPLE table ( [ID] varchar(50), [Category] varchar(25) ) INSERT INTO @TBL_EXAMPLE ([ID], [Category]) VALUES ('1234', 'Manager'), ('1234', 'Sales'), ('345', 'Sales'), ('6467', 'Manager'), ('6467', 'Sales'), ('41234', 'Sales'), ('41234', 'Manager'), ('91234', 'Sales'), ('1234', 'Admin'); select * from @TBL_EXAMPLE
Result should display like this :
ID | Category
1234 | Admin, Manager, Sales
345 |Sales
41234 |Manager, Sales
6467 |Manager, Sales
91234 |Sales
Solution 1:[1]
You can use this in MySQL:
select id, group_concat(category separator ', ') as categories
from tbl_example
group by id
Here's the format for PostgreSQL:
select id, string_agg(category, ', ') as categories
from tbl_example
group by id
Other DBMS will have something similar (search for string aggregate).
Results:
id categories
1234 Manager, Sales, Admin
345 Sales
41234 Sales, Manager
6467 Manager, Sales
91234 Sales
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Isolated |
