1
我知道如何使用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 @[email protected]) 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