How to get column values in one comma separated value
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
MYSQL: To get column values as one comma separated value use GROUP_CONCAT( )
function as
GROUP_CONCAT( `column_name` )
for example
SELECT GROUP_CONCAT( `column_name` )
FROM `table_name`
WHERE 1
LIMIT 0 , 30
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"