Skip to content

Instantly share code, notes, and snippets.

@elw00d
Created July 17, 2014 09:28
Show Gist options
  • Save elw00d/c1e6cfed063e342c2773 to your computer and use it in GitHub Desktop.
Save elw00d/c1e6cfed063e342c2773 to your computer and use it in GitHub Desktop.
Group_concat for MS SQL
Tables:
a (id, name)
b (id, name)
a_to_b (a_id, b_id)
Outputs:
a_id a_name b_ids_over_comma
select *, STUFF(
(SELECT ',' + LTRIM(RTRIM(b.name))
FROM b b join a_to_b on b_id = b.id
WHERE a_id = a.id
FOR XML PATH('')
),
1, 1, '') group_concat from a a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment