Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get column values in one comma separated value

Tags:

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
like image 930
Mohamad Amir Avatar asked Apr 01 '13 11:04

Mohamad Amir


People also ask

How do I get the values in a comma separated column?

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.

How can get column values in comma separated in MySQL?

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.


2 Answers

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"
like image 180
Taryn Avatar answered Oct 13 '22 12:10

Taryn


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
like image 28
Sagar Rawal Avatar answered Oct 13 '22 13:10

Sagar Rawal