Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

Group multiple Rows into 1 string based on ID field

$
0
0
Hello,I am trying to group multiple Rows into 1 string based on ID field. Here is my sample code:CREATE TABLE #MyLocs (RegionID int, Loc varchar(10))INSERT INTO #MyLocs (RegionID, Loc) VALUES (1, 'A101')INSERT INTO #MyLocs (RegionID, Loc) VALUES (1, 'A102')INSERT INTO #MyLocs (RegionID, Loc) VALUES (1, 'A103')INSERT INTO #MyLocs (RegionID, Loc) VALUES (2, 'B101')INSERT INTO #MyLocs (RegionID, Loc) VALUES (2, 'B102')INSERT INTO #MyLocs (RegionID, Loc) VALUES (3, 'C101')INSERT INTO #MyLocs (RegionID, Loc) VALUES (3, 'C102')INSERT INTO #MyLocs (RegionID, Loc) VALUES (3, 'C103')INSERT INTO #MyLocs (RegionID, Loc) VALUES (4, 'D101')INSERT INTO #MyLocs (RegionID, Loc) VALUES (4, 'D102')INSERT INTO #MyLocs (RegionID, Loc) VALUES (5, 'E101')INSERT INTO #MyLocs (RegionID, Loc) VALUES (5, 'E102')INSERT INTO #MyLocs (RegionID, Loc) VALUES (5, 'E103')INSERT INTO #MyLocs (RegionID, Loc) VALUES (5, 'E104')INSERT INTO #MyLocs (RegionID, Loc) VALUES (5, 'E105')INSERT INTO #MyLocs (RegionID, Loc) VALUES (6, 'F101')--SELECT * FROM #MyLocsThe outcome I getting is grouping by RegionID, but is not putting the Loc in the correct Regions. Here is my current query:SELECT RegionID, STUFF(( SELECT ', ' + Loc FROM #MyLocs FOR XML PATH(''), TYPE).value('.', 'varchar(max)') ,1,1,'') As strLocFROM #MyLocsGROUP BY RegionIDThe outcome I am hoping for would be:RegionID 1: A101,A102, A103RegionID 2: B101,B102RegionID 3: C101,C102,C103RegionID 4: D101,D102RegionID 5: E101,E102,E103,E104,E105RegionID 6: F101I am able to get close by doing the following, but am unable to group the string based on Region.Can someone help me understand how to group rows into one based on the RegionID?

Viewing all articles
Browse latest Browse all 3145

Trending Articles