Now with the latest CTP 1.x version of SQL Server vNext (I’m calling it “SQL Server 2018”) a new function is introduced to just do its reverse, i.e. Concatenate string values or expressions separated by any character.
The STRING_AGG() aggregate function takes all expressions from rows and concatenates them into a single string in a single row.
It implicitly converts all expressions to String type and then concatenates with the separator defined.
>In the example below I’ll populate a table with States and Cities in separate rows, and then try to Concatenate Cities belonging to same States:
USE tempdbGO
CREATE TABLE #tempCityState (
[State] VARCHAR(5),
[Cities] VARCHAR(50)
)
INSERT INTO #tempCityState
SELECT 'AK', 'Wynne'
UNION ALL
SELECT 'AK', 'Nashville'
UNION ALL
SELECT 'CA', 'Hanford'
UNION ALL
SELECT 'CA', 'Fremont'
UNION ALL
SELECT 'CA', 'Los Anggeles'
UNION ALL
SELECT 'CO', 'Denver'
UNION ALL
SELECT 'CO', 'Aspen'
UNION ALL
SELECT 'CO', 'Vail'
UNION ALL
SELECT 'CO', 'Teluride'
SELECT * FROM #tempCityState

>To comma separate values under a single row you just need to apply the STRING_AGG() function:
SELECTSTRING_AGG(Cities, ', ') as AllCities
FROM #tempCityState
-- Use "WITHIN GROUP (ORDER BY ...)" clause to concatenate them in an Order:
SELECT
STRING_AGG(Cities, ', ') WITHIN GROUP (ORDER BY Cities) as CitiesByStates
FROM #tempCityState

>Now to Concatenate them by States, you just need to group them by the State, like any other aggregate function:
SELECTState,
STRING_AGG(Cities, ', ') as CitiesByStates
FROM #tempCityState
GROUP BY State
-- Use "WITHIN GROUP (ORDER BY ...)" clause to concatenate them in an Order:
State,
STRING_AGG(Cities, ', ') WITHIN GROUP (ORDER BY Cities) as CitiesByStates
FROM #tempCityState
GROUP BY State

You can check more about STRING_AGG() on MSDN .