Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
mohan123
Constraint Violating Yak Guru
252 Posts |
Posted - 2012-10-25 : 08:08:55
|
| Hello all,i had a table with values like one to many relation col1 Col2 1 A1 A1 B2 A2 B3 A3 Bbut i need to get out put like col1 col2 1 A,A,B2 A,B3 A,Bcan u suggest me ????P.V.P.MOhan |
|
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-10-25 : 08:11:26
|
On SQL 2005 and greater you can use XML PATH as shown belowSELECT a.col1, STUFF(b.col2s,1,1,'') AS Col2sFROM (SELECT DISTINCT col1 FROM YourTable) a CROSS APPLY ( SELECT ','+col2 FROM YourTable b WHERE a.col1 = b.col1 FOR XML PATH('') )b(col2s); |
 |
|
|
Mike Jackson
Starting Member
37 Posts |
Posted - 2012-10-25 : 08:11:27
|
| see http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=81254 |
 |
|
|
nigelrivett
Master Smack Fu Yak Hacker
3385 Posts |
Posted - 2012-10-25 : 08:11:52
|
| see thishttp://www.nigelrivett.net/SQLTsql/CSVStringSQL.htmlselect col1, csvstr = stuff ( ( select ',' + col2 from @table t2 where t.col1 = t2.col1 for xml path('') ) ,1,1,'')from (select distinct col1 from @table) t==========================================Cursors are useful if you don't know sql.SSIS can be used in a similar way.Beer is not cold and it isn't fizzy. |
 |
|
|
bandi
Master Smack Fu Yak Hacker
2242 Posts |
Posted - 2012-10-25 : 08:32:42
|
| declare @TestTable Table(col1 int, Col2 varchar(3))INsert into @TestTableSELECT 1, 'A' union allSELECT 1, 'A' union allSELECT 1, 'B' union allSELECT 2, 'A' union allSELECT 2, 'B' union allSELECT 3, 'A' union allSELECT 3, 'B'SELECT t.col1, STUFF((SELECT ',' + s.Col2 FROM @TestTable s WHERE s.col1 = t.col1 FOR XML PATH('')),1,1,'') AS CSVFROM @TestTable AS tGROUP BY t.col1--Chandu |
 |
|
|
|
|
|
|
|