?
Solved

SQL Server 2008 Combining records into columns based on primary key

Posted on 2014-09-17
2
Medium Priority
?
162 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
[X]
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
2 Comments
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 2000 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

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

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

Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Suggested Courses

771 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