您没有任何东西将您的内部和外部引用链接到[Table]
,并且您还需要使外部引用不同。最后,您需要在子查询中没有列名,或者需要[text()]
SELECT [Code]
,[Ref]
,STUFF((SELECT DISTINCT [Value] AS [text()]
FROM [Table] AS T2
WHERE T1.Code = T2.Code -- LINK HERE
AND T2.Ref = T2.Ref -- AND HERE
FOR XML PATH ('')
),1, 1,'') AS [Values]
FROM [Table] AS T1
GROUP BY T1.Code, T1.Ref; -- GROUP BY HERE
顺便说一句,您不需要使用STUFF
,因为您没有分隔符,STUFF
通常用于从字符串的开头删除选择的分隔符。所以当你有一个类似的字符串时,value1,value2,value3
,STUFF(string, 1, 1, '')
会将第一个字符替换为''
离开你value1,value2,value3
。
您还应该使用value
xquery 方法来确保您不会被特殊字符绊倒,如果您不这样做并且尝试连接">>"
并且"<<"
您最终">><<"
不会得到您可能想要的结果,那么您会得到">><<"
,因此更好的查询是:
SELECT t1.Code,
t1.Ref,
[Values] = (SELECT DISTINCT [text()] = [Value]
FROM [Table] AS t2
WHERE T1.Code = T2.Code
AND T2.Ref = T2.Ref
FOR XML PATH (''), TYPE
).value('.', 'NVARCHAR(MAX)')
FROM [Table] AS T1
GROUP BY t1.Code, t1.Ref;
附录
根据对问题的最新编辑,您的列似乎Value
来自另一个表,通过 链接到第一个表Code
。如果有的话,这会使您的查询更简单。您不需要JOIN
,但您仍然需要确保有一个表达式将外部表链接到您的子查询的内部表。我假设这些行在第一个表中是唯一的,所以您可能不需要 group by:
SELECT t1.Code,
t1.Ref,
[Values] = (SELECT DISTINCT [text()] = t2.[Value]
FROM [Table2] AS t2
WHERE T1.Code = T2.Code
FOR XML PATH (''), TYPE
).value('.', 'NVARCHAR(MAX)')
FROM [Table] AS T1;
工作示例
CREATE TABLE #Table1 (Code CHAR(2), Ref VARCHAR(10));
INSERT #Table1 VALUES ('A1', 'Car'), ('B2', 'Truck'), ('C3', 'Van');
CREATE TABLE #Table2 (Code CHAR(2), Value VARCHAR(2));
INSERT #Table2
VALUES ('A1', 'A'), ('A1', '-'), ('A1', 'B'),
('B2', 'CC'), ('B2', 'D'), ('B2', '-'),
('C3', 'F'), ('C3', '-'), ('C3', 'G');
SELECT t1.Code,
t1.Ref,
[Values] = (SELECT DISTINCT [text()] = t2.[Value]
FROM #Table2 AS t2
WHERE T1.Code = T2.Code
FOR XML PATH (''), TYPE
).value('.', 'NVARCHAR(MAX)')
FROM #Table1 AS T1;