我有一个表有一些重复的行,我能找到它们的副本,看起来像这样
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。
答案 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;