下面我展示了两个表和结果表。
如上所示,如何以这种方式获取结果表?
select min(ID) as ID,
Val,
stuff((select ','+Cat
from Table2 as T2
where T1.Val = T2.Val
for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') as Cat
from Table2 as T1
group by Val
order by ID
您可以定义一个CLR 用户定义的聚合来执行此操作。我发布了对这种解决方案的详细描述,作为对另一个问题TSQL Comma Separation的回答。在那里,您还可以找到博客文章的链接,该文章讨论了您在开发 CLR 聚合时可能遇到的问题。
将自定义聚合部署到服务器后(我为函数命名,Concat
但您的命名可能不同),您将能够通过以下查询获得所需的结果:
SELECT Val, dbo.Concat(Cat)
FROM Table2
GROUP BY Val
DECLARE @Table1 TABLE
(
id INT
,Val VARCHAR(100)
)
DECLARE @Table2 TABLE
(
id INT
,Val VARCHAR(100)
,Cat VARCHAR(100)
)
INSERT INTO @Table1
VALUES(1,'XYZ')
INSERT INTO @Table1
VALUES(2,'abc')
INSERT INTO @Table2
VALUES(1,'XYZ','a')
INSERT INTO @Table2
VALUES(1,'abc','e')
INSERT INTO @Table2
VALUES(1,'XYZ','b')
INSERT INTO @Table2
VALUES(1,'XYZ','f')
INSERT INTO @Table2
VALUES(1,'abc','g')
SELECT t1.id,t1.Val ,( SELECT STUFF((SELECT ',' + cat FROM @Table2 t2 WHERE t2.Val = t1.val FOR XML PATH('')),1,1,''))
FROM @Table1 t1