Solved

SQL Query Syntax question

Posted on 2013-11-25
3
157 Views
Last Modified: 2013-12-05
Hello all,

I am trying to do the following.   I have a table called Customer and then I have a table called CustomerGroup 1 to Many to Customer.   The fields for example are as follows:

Table:   Customer
Fields:  CustId,  CustName, CustAddress

Table: CustomerGroup
Fields:  CustId, GroupName

I want to get all the fields from table Customer then I want a comma seperated string of all the GroupNames from CustomerGroup stripped off end comma.   How can I do this?  Sample data:

Customer
CustID 1
CustName ABC
CustAddress 12 Water St

CustomerGroup
CustID 1
GroupName A

CustID 2
GroupName B

CustID 3
GroupName C

Record would return
1,  ABC,  12 Water St, 'A,B,C'
0
Comment
Question by:sbornstein2
3 Comments
 
LVL 34

Accepted Solution

by:
Brian Crowe earned 245 total points
ID: 39676032
SELECT C.CustID, C.CustName, C.CustAddress,
      STUFF(
      (
            SELECT ', ' + CG.GroupName
            FROM CustomerGroup AS CG
            WHERE CG.CustID = C.CustID
            FOR XML PATH('')
      ), 1, 2, '') AS CustomerGroups
FROM Customer AS C
0
 
LVL 10

Expert Comment

by:HuaMinChen
ID: 39676598
Try
SELECT distinct CustID,CustName,CustAddress,
       stuff( (SELECT ', ' + GroupName
               FROM CustomerGroup
               ORDER BY 1
               FOR XML PATH('')),1 ,2 ,'')
       AS column4
 from Customer
order by 1,2;

Open in new window

0
 

Author Closing Comment

by:sbornstein2
ID: 39700164
tx
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

Performance is the key factor for any successful data integration project, knowing the type of transformation that you’re using is the first step on optimizing the SSIS flow performance, by utilizing the correct transformation or the design alternat…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how the fundamental information of how to create a table.

743 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

10 Experts available now in Live!

Get 1:1 Help Now