Solved

SQL Server 2008 Combining records into columns based on primary key

Posted on 2014-09-17
2
154 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:
ScottPletcher earned 500 total points
Comment Utility
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
Comment Utility
That was fast!!  Thanks!!
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
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…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
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.

772 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now