Solved

SQL Server 2008 Combining records into columns based on primary key

Posted on 2014-09-17
2
160 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 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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

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.
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how the fundamental information of how to create a table.

705 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