SQL Server 2008 Combining records into columns based on primary key

Posted on 2014-09-17
Last Modified: 2014-09-17
I have the dataset similar to the below dummy data

ID       Product
1         Product A
1         Product D
2         Product A
2         Product B
2         Product C

I need the result set to be:
ID           Product
1             Product A, Product D
2             Product A, Product B, Product C

I have tried XML path, but still can't get the query right, any ideas?
Question by:yanci1179
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 69

Accepted Solution

Scott Pletcher earned 500 total points
ID: 40329052
    SELECT ',' + Product
    FROM tablename tn2
        tn2.ID = tn.ID
    --ORDER BY ? --if you have an id/datetime to sequence the Products
    FOR XML PATH('')
    ), 1, 1, '') AS Products
    FROM tablename
) AS tn

Author Closing Comment

ID: 40329060
That was fast!!  Thanks!!

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Server 2012 r2 and SQL 2014 6 34
CASE Statement using different fields 8 29
Create a Calendar table 29 43
MAC Dreamweaver connect to external MS SQL Server 2 39
Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question