Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

SQL Query Syntax question

Posted on 2013-11-25
3
Medium Priority
?
167 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 980 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 11

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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
What if you have to shut down the entire Citrix infrastructure for hardware maintenance, software upgrades or "the unknown"? I developed this plan for "the unknown" and hope that it helps you as well. This article explains how to properly shut down …
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.

971 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