views:

23

answers:

1

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 report, 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.

A: 

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.

Nick Gorbikoff
Sweet! I just found a posting that is a SQL Server 2005 port for this: http://blog.shlomoid.com/2008/11/emulating-mysqls-groupconcat-function.html
j0rd4n
I'm been missing this for reporting scenarios in SQL Server for as long as I can remember. It would however advice against it for any purpose other than presenting information in a manner that is CSV. This is for instance not a solution for packing multiple things into a single column.
John Leidegren
j0rd4n - apparently there is no easy way to do it - so you can try your port - or you can try this SO answer as well - they all emulate GROUP_CONCAT - http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-ms-sql-server-2005
Nick Gorbikoff
@j0rd4n: I shiver at the very sight of `FOR XML PATH('')` doesn't that look wrong or completely misguided use of the XML support that exists in SQL Server 2005?
John Leidegren
John - you are absolutely right - that is what it I use this for - - this is a much more elegant solution in my humble opinion - than trying to get a load of data an process it in your code - since this is faster - but it should only be used to retrieve and present data - not do any modifications with it, as the benefit of the speed would be lost by the complexity of the parsing code.
Nick Gorbikoff
@John Leidegren - Yes, I agree. I commented that link without reading the full thing. Does feel a bit dirty I admit. I might not do that in production. I think I'm going to still recommend a sproc.
j0rd4n