stuff()无法正常工作

时间:2017-05-01 21:12:15

标签: sql sql-server tsql

我有以下查询(简化):

with temp1 as
(
select
table1.variable1
,table1.variable2
,table2.variable3

from table1

left join table2
on table1.variable1 = table2.variable1
)

select distinct
temp1.variable1
,temp2.variable2
,stuff((select ',' + table3.Description 
from table3 t3 where t3.variable1 = temp1.variable1 
for xml path ('')), 1, 1, '') AS 'Reason'
,table3.variable4
,table4.variable5


from temp1
left join table3 
on temp1.variable1 = table3.variabl3

left join table4
on temp1.variable1 = table4.variable4

order by variable1

stuff()/ for xml语句在行中多次复制“description”,而不是将每个“description”合并为每个variable1的1行。所以,我得到了这个:

*Reason:*  
Variable1,Unit1||Excessive,Excessive,Excessive,Excessive   
Variable1,Unit1||Unusual ,Unusual,Unusual ,Unusual   
Variable1,Unit1||Under        ,Under        ,Under        ,Under  
Variable1,Unit1||Over                            ,Over                           ,Over                            ,Over   



Instead of:  
*Reason:*  
Variable1,Unit1||Excessive, Unusual, Under, Over

3月份有人问过同样的问题,没有人回答。希望有更好的运气,因为我已经在这个问题上工作了3天了。

1 个答案:

答案 0 :(得分:0)

这是STUFF FOR XML PATH语句的预期行为,因为您正在填写stuff语句之外的列。众所周知的STUFF技巧仅在您的子选择不从DECLARE @T1 TABLE (x INT, y CHAR(1)); INSERT @T1 VALUES (1, 'a'), (1, 'b'), (1, 'c'), (2, 'd'), (3, 'e'), (3, 'f'); SELECT DISTINCT T1.x, STUFF((SELECT ',' + T1.y FROM @T1 AS T2 WHERE T2.x = T1.x FOR XML PATH ('')), 1, 1, '') FROM @T1 AS T1; 语句外部选择列时才有效。

使用以下简单的内容可以观察到同样的行为:

STUFF

问题出现是因为您在外部查询的某些部分使用DECLARE @T1 TABLE (x INT, y CHAR(1)); INSERT @T1 VALUES (1, 'a'), (1, 'b'), (1, 'c'), (2, 'd'), (3, 'e'), (3, 'f'); SELECT DISTINCT T1.x, STUFF((SELECT ',' + T2.y FROM @T1 AS T2 WHERE T2.x = T1.x FOR XML PATH ('')), 1, 1, '') FROM @T1 AS T1; ,这实际上只是将外部结果集中的列与自身连接起来(与variable1一样多次)匹配,例如4场比赛将获得你看到的4个连接。如果你有6个匹配变量2,你可以从它获得6个连接。)

对于您的问题,您要做的是确保您不选择外部列,但仍然将您的where条件与外部列匹配。例如,我通过将其更改为:

来解决上述问题
STUFF

唯一的区别是我选择T2.y(来自STUFF语句)而不是T1.y(来自外部)。

因此,在您的情况下,您将STUFF((SELECT ',' + T3.[Description] FROM table3 AS T3 WHERE T3.variable1 = temp1.variable1 FOR XML PATH ('')), 1, 1, '') AS Reason 语句修改为如下所示:

{{1}}