String_Agg() is just an aggregate function. I works the same as sum(), but instead of adding numbers together, it’s tacking on string.
If this is our table:
category | value |
---|---|
a | 1 |
a | 2 |
a | 3 |
b | 4 |
b | 5 |
b | 6 |
c | 7 |
c | 8 |
c | 9 |
and we do Sum(value) group by Category
we get (the action colum is just showing you want it’s doing)
Cat | Sum | (action) |
---|---|---|
a | 6 | 1+2+3 |
b | 15 | 4+5+6 |
c | 24 | 7+8+9 |
if we do String_agg(value,‘,’) group by Category we get:
Cat | Sum | (action) |
---|---|---|
a | 1,2,3 | 1+2+3 |
b | 4,5,6 | 4+5+6 |
c | 7,8,9 | 7+8+9 |
It’s that simple. ForXML seems complicated, because of the string manipulation.