我有一个公司,行业和company_industry_map多对多表。
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 :(得分:8)
您可以在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
答案 1 :(得分:0)
在SQL Server中,您可以创建如下函数:
declare @var nvarchar(max)
set @var = ''
select @var = @var + ',' + UserLogin from [user]
select @var