Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi ,

please tell me a sql query to perform this action

suppose following is the table i currently have :

cl1 | cl2 | keywords
c1 | cc1|
c1 | cc2|
d1 | dd1|
d1 | dd2|
suppose following is the table i want

cl1 | cl2 | keywords
c1 | cc1| cc1,cc2
c1 | cc2| cc1,cc2
d1 | dd1| dd1,dd2
d1 | dd2| dd1,dd2
Posted
Updated 3-May-12 12:30pm
v2
Comments
Maciej Los 4-May-12 4:39am    
Shankhan0, it would be great to see your qestion as "solved".
[no name] 4-May-12 15:53pm    
Hi thanks for answering
its giving many space btw items in keywords
i mean keyword is somehting like this :
"cc1 ,cc2"
how i remove this unnecessary spaces
thanks

1 solution

Try this:
Option 1:
SQL
SELECT  [cl1], STUFF( (SELECT',' + [cl2] AS 'text()'
                  FROM [A_TEST].[dbo].[Table_3] t2
                  WHERE t2.cl1 = t1.cl1
                  FOR XML PATH('')), 1, 1, '') AS [keywords]
   FROM [A_TEST].[dbo].[Table_3] t1
   GROUP BY [cl1]
   GO

Results:

cl1keywords
c1cc1,cc2
d1dd1,dd2


Option 2:
SQL
SELECT  [cl1], [cl2], STUFF( (SELECT',' + [cl2] AS 'text()'
                  FROM [A_TEST].[dbo].[Table_3] t2
                  WHERE t2.cl1 = t1.cl1
                  FOR XML PATH('')), 1, 1, '') AS [keywords]
   FROM [A_TEST].[dbo].[Table_3] t1
   GROUP BY [cl1], [cl2]
   GO


Results:

cl1cl2keywords
c1cc1cc1,cc2
c1cc2cc1,cc2
d1dd1dd1,dd2
d1dd2dd1,dd2



More at:
T-SQL Convert rows into single column[^]

Related topics:
STUFF()[^]
FOR clause[^]
COLEASCE[^]
 
Share this answer
 
v3
Comments
Kschuler 3-May-12 16:53pm    
I don't think that's right...it looks the contents of the "keywords" column isn't cl1 + cl2...but rather a combo of cl2 values where cl1 matches.
Maciej Los 3-May-12 17:13pm    
Now i see the difference. cl1 = c1, cl2 = cc1, but keywords = {cc1, cc2}. I'll correct my solution. Thank you ;)
[EDIT]
Done! Sorry for my previous, bad answer.
[/EDIT]
VJ Reddy 3-May-12 19:54pm    
Good answer. 5!
Maciej Los 4-May-12 3:05am    
Thank you, VJ ;)
Sandeep Mewara 4-May-12 2:33am    
Good answer. 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900