4

I have a company, industry, and company_industry_map many-to-many table.

company_id | company_name
1            Goldman Sachs
2            Microsoft

industry_id | industry
4             Technology
5             Finance
6             Banking

company_id | industry_id
1            5
1            6
2            4

I'd like to write a query that joins all of the industries into a comma separated list like this:

company_id | industries
1            Finance, Banking
2            Technology

Here's my general query that I'm trying to write:

SELECT company_id, 
       xxx AS industries 
  FROM company c, 
       company_industry_map m 
 WHERE c.company_id = m.company_id
4
  • What database are you using? SQL server, MySQL, etc Commented Feb 28, 2014 at 14:04
  • 1
    You can look at this: stackoverflow.com/questions/8700961/… Commented Feb 28, 2014 at 14:08
  • Specifically look at the answer(Rick S comment) with the highest score using the STUFF command Commented Feb 28, 2014 at 14:09
  • 1
    Please stop using the sql antipattern of implicit joins. They are a very POOR technique making it harder to maintain systems and leading to more risky code that can contain errors such as accidnetal cross joins that explicit syntax will not allow. Commented Feb 28, 2014 at 14:38

2 Answers 2

12

You can use something like this in SQL Server

select co.CompanyID, AllIndustries = 
       (select (cast(industry as varchar(200))+',') as [text()]
       FROM company c, 
       company_industry_map m 
       WHERE c.company_id = m.company_id and c.company_id = co.company_id 
       order by industry_id for XML PATH(''))
from Companies co
Sign up to request clarification or add additional context in comments.

Comments

0

In SQL Server you can create a function like this:

declare @var nvarchar(max)

set @var = ''
select @var = @var  + ',' + UserLogin from [user] 

select @var

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.