将Raws转换为Columns中的字符串-仅当唯一时

时间:2019-01-28 07:40:30

标签: tsql

在另一篇文章中,我询问了如何改进当前返回的查询: enter image description here

现在我有另一个问题。如何使用仅在整个字符串中唯一的ErrorCode修改代码以具有最终的簇字符串,因此对于第1行,仅返回一个B,C,A(跳过第二个C和第二个A)。

此致

Arek

    DECLARE @table1 TABLE
(
    [Case] INT,
    ErrorCode CHAR(1),
    [Date] varchar(20)
);

INSERT INTO @table1
VALUES
(1, 'A', '2018-01-25'),
(1, 'B', '2018-01-15'),
(1, 'C', '2018-01-15'),
(1, 'A', '2018-01-15'),
(1, 'C', '2018-01-15'),
(1, 'A', '2018-01-15'),
(2, 'D', '2018-01-26'),
(2, 'A', '2018-01-26'),
(2, 'D', '2018-01-25'),
(2, 'C', '2018-01-24'),
(2, 'C', '2018-01-24');

SELECT *
FROM @table1;

SELECT tabel2.[Case],
       tabel2.[Date],
       STUFF(
       (
           SELECT ', ' + ErrorCode
           FROM @table1 t1
           WHERE t1.[Case] = tabel2.[Case]
                 AND t1.[Date] = tabel2.[Date]
           FOR XML PATH('')
       ),
       1,
       1,
       ''
            ) AS [ErrorCode]
FROM
(SELECT DISTINCT [Case], [Date] FROM @table1) AS tabel2
ORDER BY tabel2.[Case],
         tabel2.[Date];

1 个答案:

答案 0 :(得分:1)

如果我正确理解了这一点,那么向返回CSV的子查询中添加DISTINCT就足够了:

   STUFF(
   (
       SELECT ** DISTINCT **  ', ' + ErrorCode --remove **
       FROM @table1 t1
       WHERE t1.[Case] = tabel2.[Case]
             AND t1.[Date] = tabel2.[Date]
       FOR XML PATH('')
   ),