Skip to content

Instantly share code, notes, and snippets.

@kevinwucodes
Last active November 6, 2018 23:35
Show Gist options
  • Select an option

  • Save kevinwucodes/519077444ed5bd91ea926cc38285f157 to your computer and use it in GitHub Desktop.

Select an option

Save kevinwucodes/519077444ed5bd91ea926cc38285f157 to your computer and use it in GitHub Desktop.
sql - learn - string aggregation prior to STRING_AGG()
--https://stackoverflow.com/questions/31211506/how-stuff-and-for-xml-path-work-in-sql-server
--https://stackoverflow.com/questions/273238/how-to-use-group-by-to-concatenate-strings-in-sql-server
;with colors as (
select id, name, color
from (
values
(1, 'kevin', 'blue')
,(2, 'kevin', 'red')
,(3, 'aria', 'pink')
,(4, 'wendy', 'orange')
) colors (id, name, color)
)
select
name
,STUFF(
(
SELECT ', ' + color
FROM colors
WHERE name = c.name --this part joins this subquery with the outer query
FOR XML PATH(''),TYPE --creates XML node without tags
).value('(./text())[1]','VARCHAR(MAX)') --converts the XML path back to varchar(max) ???
,1, 2, '') AS NameValues --this part (using STUFF) replaces the leading ', ' in the string with a blank space
from colors c
group by name
/*
name NameValues
----- ----------------
aria pink
kevin blue, red
wendy orange
(3 row(s) affected)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment