Display column of different rows as column of a single row:
Problem:
Displaying column value of different rows in a single row with a separator comma, hyphen, semicolon etc.
Solution:
In the below solution, refer the table "PRODUCT". In the table there are multiple products for a client and we are trying to display products as comma separated value for each client as a single row.
- Mechanism
- Microsoft Updates
- Microsoft Word
- A Single
CREATE TABLE PRODUCT ( ClientNumber VARCHAR(50) , ClientName VARCHAR(50) , Product VARCHAR(50) ) INSERT INTO PRODUCT SELECT '100SON', 'Sony', 'TV' UNION ALL SELECT '100SON','Sony', 'DVD Player' UNION ALL SELECT '100SON','Sony', 'Cell Phone' UNION ALL SELECT '200KEN','Kenmoore', 'Microwave' UNION ALL SELECT '200KEN','Kenmoore', 'Dryer'
Table Data:
Now, lets write a query to display the data of product as a single row on the basis of Client Number and Client Name.
SELECT ClientNumber, ClientName , STUFF(( SELECT ',' + Product FROM PRODUCT b WHERE a.ClientNumber = b.ClientNumber FOR XML PATH('')
), 1, 1, '') AS ProductList FROM PRODUCT a GROUP BY ClientNumber, ClientName
Worthful Sql server tutorial. Appreciate a lot for taking up the pain to write such a quality content on SQL server tutorial. Just now I watched this similar
ReplyDeleteSql Server tutorial and I think this will enhance the knowledge of other visitors for sureSql Server Online Training
thank your valuable content.we are very thankful to you.one of the recommanded blog.which is very useful to new learners and professionals.content is very useful for hadoop learners
ReplyDeleteBest Spring Classroom Training Institute
Best Devops Classroom Training Institute
Best Corejava Classroom Training Institute
Best Oracle Classroom Training Institute
Best Oracle Classroom Training Institute
Thanks For Sharing The Information The Information Shared Is Very Valuable Please Keep Updating Us Time Just Went On Reading The article sql server Online Course
ReplyDeletethanks for sharing, very informative for learner, Full Stack Classes In Amravati
ReplyDelete