Solved

CTE Group By One Column and Return Many Column?

Posted on 2014-02-12
2
298 Views
Last Modified: 2014-02-15
There must be a way to Group By 1 column without including every column. I don't want to Group By t1.id or t2.id, only t1.Company_Name .

Note: CTE is just an idea that might work, I don't have CTE code here.

Note: I have more columns not included in this example for brevity sake...

[Table1]
Company_Name           States          Contact_Name
My Business                  KY; OH             John Doe
My Business                  KY; OH             Mark Smith
My Business                  KY; OH             Bill Jones
My Business                  KY; OH             Dan Moore

[Query]
Select
    t1.Company_Name ,
   Stuff ((SELECT '; ' + s.name AS [text()]
           FROM States s
           WHERE (t1.id = s.id) FOR XML path('')), 1, 1, '') AS [States],
 
   Stuff ((SELECT '; ' + c.Contact_Name AS [text()]
           FROM Contacts c
           WHERE (t2.id = c.id) FOR XML path('')), 1, 1, '') AS [Contacts],
From
    Companies t1
    Join Contacts t2 on t1.id = t2.ContactID

Group By
    t1.Company_Name ],   --I only want to Group on this column
    t1.id,                              --don't want to group by
    t2.id                               --don't want to group by
0
Comment
Question by:WorknHardr
2 Comments
 
LVL 45

Accepted Solution

by:
Kdo earned 500 total points
ID: 39853823
Hi WorkN,

Unfortunately, this functionality doesn't exist in SQL Server.  It does in MySQL, but most DBMS haven't incorporated it.

You'll have to run the small query with the correct GROUP BY and then LEFT or INNER join the table back to that result.


Good Luck,
Kent
0
 

Author Closing Comment

by:WorknHardr
ID: 39861346
thx
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

Suggested Solutions

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
I have a large data set and a SSIS package. How can I load this file in multi threading?
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 extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

773 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