Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Need to

Author  Topic 

helixpoint
Constraint Violating Yak Guru

291 Posts

Posted - 2011-12-09 : 13:25:02





I have a table with values as follows:

SELECT deptno, ename FROM emp ORDER BY deptno, ename;

DEPTNO ENAME
------ ----------
10 CLARK
10 KING
10 MILLER
20 ADAMS
20 FORD
20 JONES
20 SCOTT
20 SMITH
30 ALLEN
30 BLAKE
30 JAMES
30 MARTIN
30 TURNER
30 WARD

14 rows selected.
but I need them in the following less convenient format:

DEPTNO ENAME
------ -----------------------------------------
10 CLARK, KING, MILLER
20 ADAMS, FORD, JONES, SCOTT, SMITH
30 ALLEN, BLAKE, JAMES, MARTIN, TURNER, WARD


Dave
Helixpoint Web Development
http://www.helixpoint.com

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-12-09 : 13:34:18
http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-10 : 08:12:37
of the methods, the most popular one is blackbox XML method used with STUFF
see

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=81254

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

johntech
Yak Posting Veteran

51 Posts

Posted - 2011-12-13 : 09:28:19
So you want to group by from xml ,show below example
http://stackoverflow.com/questions/273238/how-to-use-group-by-to-concatenate-strings-in-sql-server

CREATE TABLE #YourTable ([ID] INT, [Name] CHAR(1), [Value] INT)

INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'A',4)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',8)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)

SELECT
[ID]
, STUFF((SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) FROM #YourTable WHERE (ID = Results.ID) FOR XML PATH ('')),1,2,'') AS NameValues
FROM #YourTable Results
GROUP BY ID

DROP TABLE #YourTable



Go to Top of Page
   

- Advertisement -