Is it possible to "merge" the values of multiple records into a single field without using a stored procedure?
A co-worker posed this question to me, and I told them, "No, you'll need to write a sproc for that". But I thought I'd give them a chance and put this out to the community.
Essentially, they have a table with keys mapping to multiple values. For a re开发者_高级运维port, they want to aggregate on the key and "mash" all of the values into a single field. Here's a visual:
--- -------
Key Value
--- -------
1 A
1 B
1 C
2 X
2 Y
The result would be as follows:
--- -------
Key Value
--- -------
1 A,B,C
2 X,Y
They need this in SQLServer 2005. Again, I think they need to write a stored procedure, but if anyone knows a magic out-of-the-box function that does this, I'd be impressed.
I'm not sure if sql-server supports group_concat - but that's what you would use in MySQL:
SELECT key, GROUP_CONCAT(value) FROM table_name GROUP BY key
I use this all the time.
Also to add to this GROUP_CONCAT by default will separate value using commas, but you can format it any way you want - interjecting text, calculations or values from other columns.
精彩评论