Solved

SQL Server 2008 Combining records into columns based on primary key

Posted on 2014-09-17
2
157 Views
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?
0
Comment
Question by:yanci1179
2 Comments
 
LVL 69

Accepted Solution

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

Author Closing Comment

by:yanci1179
ID: 40329060
That was fast!!  Thanks!!
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how the fundamental information of how to create a table.

789 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