代码:
DECLARE @GroupByCnt INT = 3;
CREATE TABLE #Temp (ID VARCHAR(15))
INSERT INTO #Temp
SELECT '123'
UNION ALL SELECT '123'
UNION ALL SELECT '234'
UNION ALL SELECT '345'
UNION ALL SELECT '456'
UNION ALL SELECT '456'
UNION ALL SELECT '456'
UNION ALL SELECT '567'
UNION ALL SELECT '678'
UNION ALL SELECT '789'
UNION ALL SELECT '890'
UNION ALL SELECT '901'
UNION ALL SELECT '901'
SELECT DISTINCT STUFF((
SELECT ',' + ID
FROM #Temp T1
WHERE T1.ID = T2.ID
FOR XML PATH('')
), 1, 1, '') ID
FROM #Temp T2
DROP TABLE #Temp
当前输出:
ID
123,123
234
345
456,456,456
567
678
789
890
901,901
期望的输出:
ID
123,234,345
456,567,678
789,890,901
目标:
我想连接一组唯一记录(以逗号分隔)。
所以在上面的例子中,我想一次连接3个唯一记录(而不是完全连接)。那里有9条独特的记录;因为我希望它们按3分组,我最终会得到3条记录,其中每条输出记录中有3条记录连接(按ID排序)。
答案 0 :(得分:3)
看起来只是演示文稿,应该在应用程序层完成。
<小时/> 您可以使用
DENSE_RANK()
和整数除法来创建组:
WITH cte AS
(
SELECT DISTINCT ID, (DENSE_RANK() OVER(ORDER BY ID) - 1)/3 AS grp
FROM #Temp
)
SELECT DISTINCT STUFF((SELECT ',' + ID
FROM cte T1
WHERE T1.grp = T2.grp
ORDER BY ID
FOR XML PATH('')
), 1, 1, '') ID
FROM cte T2;
的 LiveDemo
强>
输出:
╔═════════════╗
║ ID ║
╠═════════════╣
║ 123,234,345 ║
║ 456,567,678 ║
║ 789,890,901 ║
╚═════════════╝