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,
OTHER_KEYS_EXCEPT_MIN = STUFF(
(SELECT ',' + CONVERT(varchar(11), h2.HPKEY)
FROM @Holder AS h2
WHERE h2.HSOMEVALUE = h.HSOMEVALUE
AND h2.HPKEY > h.MINKEY
FOR XML PATH(''),
TYPE).value(N'./text()[1]', N'varchar(max)'), 1, 1, N'')
FROM
(
SELECT HSOMEVALUE, MINKEY = MIN(HPKEY)
FROM @Holder GROUP BY HSOMEVALUE
) AS h
ORDER BY SomeValue;
在 SQL Server 2017+ 上,这不那么混乱,恕我直言,有STRING_AGG()
:
SELECT SomeValue = h.HSOMEVALUE, h.MINKEY,
OTHER_KEYS_EXCEPT_MIN = STRING_AGG(h2.HPKEY, ',')
FROM @holder AS h2
INNER JOIN
(
SELECT HSOMEVALUE, MINKEY = MIN(HPKEY)
FROM @Holder GROUP BY HSOMEVALUE
) AS h
ON h.HSOMEVALUE = h2.HSOMEVALUE
WHERE h2.HPKEY > h.MINKEY
GROUP BY h.HSOMEVALUE, h.MINKEY
ORDER BY SomeValue;