连接两个表的字符串的聚合函数?
Posted
技术标签:
【中文标题】连接两个表的字符串的聚合函数?【英文标题】:Aggregate function to concatenate strings joining two tables? 【发布时间】:2014-02-11 16:07:32 【问题描述】:我知道如何使用 for xml auto 连接聚合查询中的字段。但是我在扩展该查询以使用两个表时遇到了一些问题,以下示例不起作用
例如
set nocount on;
declare @FirstTable table (RowID int, LinkedField int)
insert into @FirstTable VALUES (1,1)
insert into @FirstTable VALUES (2,2)
insert into @FirstTable VALUES (2,3)
insert into @FirstTable VALUES (2,4)
insert into @FirstTable VALUES (3,5)
insert into @FirstTable VALUES (3,1)
declare @SecondTable table (LinkedField int, Field2Show int)
insert into @SecondTable VALUES (1,11)
insert into @SecondTable VALUES (2,12)
insert into @SecondTable VALUES (3,13)
insert into @SecondTable VALUES (4,14)
insert into @SecondTable VALUES (5,15)
/*
output i need:
RowID ChildValues
----------- -------------------
1 11
2 12,13,14
3 11,15
*/
SELECT t1.RowID,
STUFF(
( SELECT ', ' + t2.Field2Show
FROM
( SELECT @SecondTable.Field2Show, @SecondTable.LinkedField
FROM @SecondTable
INNER JOIN @FirstTable ON @FirstTable.LinkedField=@SecondTable.LinkedField ) t2
WHERE t1.LinkedField = t2.LinkedField
ORDER BY t2.Field2Show
FOR XML PATH(''), TYPE).value('.','varchar(max)') ,1,2, '') AS ChildValues
FROM @FirstTable t1
GROUP BY t1.RowID
【问题讨论】:
【参考方案1】:您应该能够将问题更改为以下内容以获得最终结果:
SELECT distinct t1.RowID,
STUFF(
(SELECT ', ' + cast(t2.Field2Show as varchar(10))
FROM @SecondTable t2
INNER JOIN @FirstTable t -- join on @FirstTable based on LinkedField
on t.LinkedField = t2.LinkedField
WHERE t1.RowID = t.RowID -- associate the RowId from FirstTable to concatenate
ORDER BY t2.Field2Show
FOR XML PATH(''), TYPE).value('.','varchar(max)') ,1,2, '') AS ChildValues
FROM @FirstTable t1;
见SQL Fiddle with Demo
【讨论】:
以上是关于连接两个表的字符串的聚合函数?的主要内容,如果未能解决你的问题,请参考以下文章