Click here to Skip to main content
15,921,062 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
i have a table like

SQL
NAME        CLASS        CODE
-------------------------------
Suresh      MCA           111
Ramesh     MBBS           111
Binai       MSc           222
Siva        BBC           333
Vali        MCA           333


i want a query it converts below result table based on about table using code column

SQL
NAME                CLASS                CODE
-----------------------------------------------
Suresh,Ramesh      MCA,MBBS               111
Binai                MSc                  222
Siva,Vali          BBC,MCA                333


Pleas give me a sql query for this

Thanks
Sudheer
Posted
Updated 4-Dec-11 22:20pm
v2
Comments
[no name] 5-Dec-11 4:18am    
How did that happen? This isn't realistic my friend.
sudheer.learner 5-Dec-11 4:22am    
can we write Stored procedure for this?
D K N T H 5-Dec-11 4:19am    
complex query right?
D K N T H 5-Dec-11 4:20am    
added code tags

1 solution

This is one of the option to do this if you are using SQL 2005:

SQL
Create Table your_table_name (ID INT, Value varchar(20), value2 varchar(20))

INSERT INTO your_table_name VALUES(111,'MCA','Suresh')
INSERT INTO your_table_name VALUES(111,'MBBS','Ramesh')
INSERT INTO your_table_name VALUES(222,'MSC','Binal')
INSERT INTO your_table_name VALUES(333,'BBC','Siva')
INSERT INTO your_table_name VALUES(333,'MCA','Vali')

SELECT * from your_table_name

SELECT ID,
SUBSTRING((select ' ,'+ CAST(value AS VARCHAR) from your_table_name b WHERE a.ID = b.ID FOR XML PATH('')),3,100) [Name1],
SUBSTRING((select ' ,'+ CAST(value2 AS VARCHAR) from your_table_name b WHERE a.ID = b.ID FOR XML PATH('')),3,100) [Name2]
FROM your_table_name a
GROUP BY a.ID


not sure how efficient it is..
 
Share this answer
 
Comments
Amir Mahfoozi 5-Dec-11 6:57am    
Brilliant, my 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