按列

时间:2015-04-24 13:33:51

标签: sql sql-server tsql sql-server-2008-r2 sql-server-group-concat

我有下表:

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

我离开了示例here,但无处可去。以下是我提出的建议:

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]

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

1 个答案:

答案 0 :(得分:3)

您没有将您的内部和外部引用链接到[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方法来确保你没有被特殊字符绊倒,如果你没有尝试连接">>""<<"你不会像你想要的那样得到">><<",你会得到"&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,但仍需要确保有一个表达式将外部表与子查询的内部表链接起来。我假设第一个表中的行是唯一的,因此您可能不需要该组:

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;