0

Possible Duplicate:
Concatenate many rows into a single text string?
How to use GROUP BY to concatenate strings in SQL Server?

I have a table customer (id, person_id, account number), id is primary key. For example

id   person_id    account number
1    0001         acc00011
2    0001         acc00012
3    0002         acc00021

Now I want to write a query to self join the table to get all the account numbers for each person. The result table should be

person_id    account
0001         acc00011, acc00012
0002         acc00021

How do I write the query?

Community
  • 1
  • 1
GLP
  • 3,441
  • 20
  • 59
  • 91

2 Answers2

3

You can't do that unless you want accounts concatenated in a single string by person_id. See this questions:

Community
  • 1
  • 1
Anri
  • 6,175
  • 3
  • 37
  • 61
3

Use a correlated subquery with FOR XML PATH and GROUP BY for the concatenation. Use STUFF to remove preceding comma from results.

See example here: http://sqlfiddle.com/#!3/e5bd0/5

Bryan
  • 17,112
  • 7
  • 57
  • 80