1

我有下表:

Code    Ref     Value
A1      Car     A
A1      Car     -
A1      Car     B
B2      Truck   CC
B2      Truck   D
B2      Truck   -
C3      Van     E
C3      Van     F
C3      Van     -
C3      Van     G

我要实现的目标是一个连接字符串,将所有值组合在一起,如下所示:

Code   Ref    Value
A1     Car    A-B
B2     Truck  CCD-
C3     Van    EF-G

我离开了这里的例子,但一无所获。这是我想出的:

SELECT [Table].[Code]
, [Table].[Ref]
, STUFF((SELECT DISTINCT [Value]
  FROM [Table2]
  FOR XML PATH ('')),1, 1,'') AS Values
FROM [Table]
LEFT JOIN [Table2] ON
[Table2].[Code] = [Table].[Code]

我哪里错了?有没有更有效的方法来做到这一点?

4

1 回答 1

5

您没有任何东西将您的内部和外部引用链接到[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,value3STUFF(string, 1, 1, '')会将第一个字符替换为''离开你value1,value2,value3

您还应该使用valuexquery 方法来确保您不会被特殊字符绊倒,如果您不这样做并且尝试连接">>"并且"<<"您最终">><<"不会得到您可能想要的结果,那么您会得到"&gt;&gt;&lt;&lt;",因此更好的查询是:

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;
于 2015-04-24T13:38:58.737 回答