从逗号分隔的字符串中删除值

时间:2013-04-10 22:22:30

标签: sql-server-2008-r2

我有一个表有一些重复的行,我能找到它们的副本,看起来像这样

CREATE TABLE Holder
(
    HPKEY INT,
    HSOMEVALUE VARCHAR(50)
);

INSERT INTO HOLDER (HPKEY,HSOMEVALUE)
VALUES
(1,'abc'),
(2,'abc'),
(5,'abc'),
(7,'xyz'),
(9,'xyz')

现在我必须将结果集转换为这种格式

Somvalue         MINKEY           OTHER_KEYS_EXCEPT_MIN
abc               1               2,5
xyz               7                9

但我得到了第三栏中的所有密钥。

我为此创建了SQLFIDDLER

1 个答案:

答案 0 :(得分:1)

DECLARE @Holder TABLE
(
    HPKEY INT,
    HSOMEVALUE VARCHAR(50)
);

INSERT INTO @HOLDER (HPKEY,HSOMEVALUE)
VALUES
(1,'abc'),
(2,'abc'),
(5,'abc'),
(7,'xyz'),
(9,'xyz');

SELECT SomeValue = HSOMEVALUE, 
  MINKEY = m, 
  OTHER_KEYS_EXCEPT_MIN = STUFF((SELECT ',' + RTRIM(HPKEY)
      FROM @Holder AS h2 WHERE HSOMEVALUE = h.HSOMEVALUE
      AND HPKEY <> m FOR XML PATH, TYPE
   ).value('.[1]', 'nvarchar(max)'), 1, 1, '')
FROM (SELECT HSOMEVALUE, m = MIN(HPKEY)
 FROM @Holder GROUP BY HSOMEVALUE) AS h
ORDER BY SomeValue;