-1

I have a T-SQL query that returns a result of two rows with the same contact name but in one of the columns is different:

Contact Name   BuildingID    ClassID
------------------------------------
XXXX              720         3505
XXXX              720         3650

I need to combine both ClassID values into the ClassID column like this:

Contact Name   BuildingID    ClassID
----------------------------------------
XXXX              720        3505;3650
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • That's a SQL Anti Pattern. One field should contain one value. Why do you want to do this? – MatBailie Sep 26 '16 at 13:51
  • 1
    Possible duplicate of [How to make a query with group\_concat in sql server](http://stackoverflow.com/questions/17591490/how-to-make-a-query-with-group-concat-in-sql-server) --- Concatenating multiple values into a single field in a view is a pretty common requirements. Some RDBMS have built in functionality (Group_Concat in MySQL or string_agg in Oracle, for instance). With SQL Server you to use `stuff()` and `cross apply` to get the job done. Check out that link and it should get you close to what you need. – JNevill Sep 26 '16 at 14:03

2 Answers2

0

You can try like this using stuff and xml Path

SELECT ContactName, BuildingID,
   STUFF((SELECT ','+CONVERT(varchar(20),classid) FROM Contacts where contactname= c.ContactName and BuildingId = c.BuildingID
           FOR XML PATH('')),1,1,'') AS ClassId
FROM Contacts C
Group by ContactName, BuildingId
Kannan Kandasamy
  • 13,405
  • 3
  • 25
  • 38
0
CREATE TABLE #XX
(
    ContactName VARCHAR(10) ,
    BuildingId INT,
    ClassId INT
)


INSERT INTO #XX VALUES ('XXXX',720,3505)
INSERT INTO #XX VALUES ('XXXX',720,3650)


SELECT DISTINCT ContactName,BuildingId,STUFF((
                SELECT  ';' + CAST(ClassId AS VARCHAR(10))
                FROM #XX FOR XML PATH('')
                ), 1, 1, '') AS ClassId
                FROM #XX
Deepthi
  • 86
  • 1
  • 7