Consider the following table:
CREATE TABLE EMPLOYEE(ENAME VARCHAR(45),DEPT VARCHAR(45))
INSERT INTO EMPLOYEE VALUES ('Mahesh','IT')
INSERT INTO EMPLOYEE VALUES ('Suresh','ACCOUNTS')
INSERT INTO EMPLOYEE VALUES ('Prakesh','ACCOUNTS')
INSERT INTO EMPLOYEE VALUES ('Rajesh','IT')
INSERT INTO EMPLOYEE VALUES ('Kamesh','ACCOUNTS')
INSERT INTO EMPLOYEE VALUES ('Prajnesh','IT')
INSERT INTO EMPLOYEE VALUES ('Sateesh','IT')
INSERT INTO EMPLOYEE VALUES ('Venkatesh','SALES')
INSERT INTO EMPLOYEE VALUES ('Rupesh','ACCOUNTS')
INSERT INTO EMPLOYEE VALUES ('Yagnesh','SALES')
Using STRING_AGG() Function (SQL Server 2017 or later)
SELECT DEPT, STRING_AGG(ENAME, ',') AS ENAME_LIST
FROM EMPLOYEE
GROUP BY DEPT
Using STUFF AND FOR XML PATH
SELECT T1.DEPT, STUFF((SELECT ','+ENAME
FROM EMPLOYEE T2
WHERE T2.DEPT=T1.DEPT
FOR XML PATH('')),1,1,'') AS ENAME_LIST
FROM EMPLOYEE T1
GROUP BY DEPT
Using REPLACE AND FOR JSON PATH, WITHOUT_ARRAY_WRAPPER (SQL Server 2016 or later)
SELECT T3.DEPT, REPLACE(REPLACE(T3.ENAME,'{"ENAME":"',''),'"}','') AS ENAME_LIST
FROM (
SELECT DEPT, (SELECT ENAME AS [ENAME]
FROM EMPLOYEE T2
WHERE T2.DEPT=T1.DEPT
FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) ENAME
FROM EMPLOYEE T1
GROUP BY DEPT) T3
Using CTE and ROW_NUMBER Function
;WITH
ELIST1(DEPT, ENAME, RID)
AS
(
SELECT DEPT, ENAME, ROW_NUMBER() OVER (PARTITION BY DEPT ORDER BY ENAME)
FROM EMPLOYEE
)
,
ELIST2(DEPT, ENAME_LIST, RID)
AS
(
SELECT DEPT, TRY_CONVERT(VARCHAR(MAX),ENAME), 1
FROM ELIST1
WHERE RID=1
UNION ALL
SELECT ELIST2.DEPT, TRY_CONVERT(VARCHAR(MAX),ELIST2.ENAME_LIST+','+ELIST1.ENAME), ELIST2.RID+1
FROM ELIST2
INNER JOIN
ELIST1 ON ELIST1.DEPT=ELIST2.DEPT AND ELIST1.RID=ELIST2.RID+1
)
SELECT DEPT, MAX(ENAME_LIST) AS ENAME_LIST
FROM ELIST2
GROUP BY DEPT
Output (Output is same for all above examples)DEPT | ENAME_LIST |
---|---|
ACCOUNTS | Kamesh,Prakesh,Rupesh,Suresh |
IT | Mahesh,Prajnesh,Rajesh,Sateesh |
SALES | Venkatesh,Yagnesh |
Let me know if you have any questions, suggestions or comments.