2014-02-28 84 views
2

我有一個公司,行業和company_industry_map多對多表。SQL Server將結果以逗號分隔列表

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 

我想編寫一個連接所有的行業爲逗號分隔的列表這樣的查詢:

company_id | industries 
1   Finance, Banking 
2   Technology 

這裏是我的,我想寫通用查詢:

SELECT company_id, 
     xxx AS industries 
    FROM company c, 
     company_industry_map m 
WHERE c.company_id = m.company_id 
+0

你使用了哪個數據庫? SQL服務器,MySQL等 –

+0

我正在使用SQL Server –

+1

你可以看看這個:http://stackoverflow.com/questions/8700961/using-coalesce-function-to-make-values-separated-with-commas –

回答

6

你可以在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 
0

在SQL Server中,你可以創建這樣一個功能:

declare @var nvarchar(max) 

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

select @var