I have a table which contains rows like below
ID User Department
1 User1 Admin
2 User1 Accounts
3 User2 Finance
4 User3 Sales
5 User3 Finance
I need a select query which results following format
ID User Department
1 User1 Admin,Accounts
2 User2 Finance
3 User3 Sales, Finance
Convert column list to comma separated list with TEXTJOIN function. The Excel TEXTJOIN function joins multiple values from a row, column or a range of cells with specific delimiter. Note that the function is only available in Excel for Office 365, Excel 2021, and Excel 2019.
In MySQL, you can return your query results as a comma separated list by using the GROUP_CONCAT() function. The GROUP_CONCAT() function was built specifically for the purpose of concatenating a query's result set into a list separated by either a comma, or a delimiter of your choice.
You tagged the question with both sql-server and plsql so I will provide answers for both SQL Server and Oracle.
In SQL Server you can use FOR XML PATH
to concatenate multiple rows together:
select distinct t.[user],
STUFF((SELECT distinct ', ' + t1.department
from yourtable t1
where t.[user] = t1.[user]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,2,'') department
from yourtable t;
See SQL Fiddle with Demo.
In Oracle 11g+ you can use LISTAGG
:
select "User",
listagg(department, ',') within group (order by "User") as departments
from yourtable
group by "User"
See SQL Fiddle with Demo
Prior to Oracle 11g, you could use the wm_concat
function:
select "User",
wm_concat(department) departments
from yourtable
group by "User"
In Sql Server you can use it.
DECLARE @UserMaster TABLE(
UserID INT NOT NULL,
UserName varchar(30) NOT NULL
);
INSERT INTO @UserMaster VALUES (1,'Rakesh')
INSERT INTO @UserMaster VALUES (2,'Ashish')
INSERT INTO @UserMaster VALUES (3,'Sagar')
SELECT * FROM @UserMaster
DECLARE @CSV VARCHAR(MAX)
SELECT @CSV = COALESCE(@CSV + ', ', '') + UserName from @UserMaster
SELECT @CSV AS Result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With