Skip to content

Instantly share code, notes, and snippets.

@alevyinroc
Created February 2, 2020 21:07
Show Gist options
  • Select an option

  • Save alevyinroc/81161fd794f218e0ab2b82c5c6028fb7 to your computer and use it in GitHub Desktop.

Select an option

Save alevyinroc/81161fd794f218e0ab2b82c5c6028fb7 to your computer and use it in GitHub Desktop.
-- Original version
SELECT DISTINCT location
,stuff((
SELECT ',' + cast(a2.npa AS CHAR(3))
FROM areacodes a2
WHERE a2.location = a.location
order by a2.npa
FOR XML PATH('')
), 1, 1, N'') AS areacodes
FROM areacodes a
ORDER BY location;
-- SQL Server 2017 version
SELECT location
,string_agg(npa, ',') within group (order by npa) AS AreaCodes
FROM areacodes
GROUP BY location
ORDER BY location;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment