views:

52

answers:

2

Hello all

i have a table in SQL 2008 as

ID     Items
1      A
1      B
2      C
3      D
3      B

i would like to get the result as

ID    Items
1     A,B
2     C
3     B,D

I have used cursors but it has considerably slowed the process , can i achieve the above result using group by query or through any other way.

Thanks and Regards

Kapil

+2  A: 

You are looking for a way to concatenate the results. I don't think MSSQL has a function for that, but here's a very nice tutorial on how to create a method like that: http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

WoLpH
Thanks WolpHThis thing worked for me,,,I took the "Cursor Solution" in the above link.
kapil Yadav
A: 

I think

GROUP_CONCAT

is the function you are looking for. Something like

SELECT id,
       GROUP_CONCAT (DISTINCT Items ORDER BY Items SEPARATOR ',')
    FROM my_table
    GROUP BY id;
Brian Hooper
`GROUP_CONCAT` is a MySQL command, and as far as I am aware, it is not available in SQL Server 2008.
Mike
True, no group_concat() in SQL Server 2008. WoLpH's answer seems to be the one to go with.
Luther Blissett
Oops. Sorry, chaps. Didn't notice that bit about SQL Server 2008. APC has thoughtfully corrected the tags.
Brian Hooper
Thanks everyone for your quick responses. WoLpH's comment was fruitfull. Like WoLpH i once again would like to direct users having this kind of issue to : http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/ and check for the "cursor solution".Best RegardsKapil
kapil Yadav