你问得太多了,让我们先关注一下这个要求:
Packagings: 1-001, 1-002, 1-003, 1-004, 1-007, 1-008, 2-001
Expected: 1-001 to 1-004, 1-007 to 1-008, 2-001
与
DelimitedSplit8K
DECLARE @packagings VARCHAR(1000) = '1-001, 1-002, 1-003, 1-004, 1-007, 1-008, 2-001';
SELECT STUFF(
(
SELECT
', '+
CASE
WHEN MIN(g.txt) = MAX(g.txt)
THEN CAST(g.txtGroup AS VARCHAR(100))+'-'+CAST(MIN(g.txt) AS VARCHAR(100))
ELSE CAST(g.txtGroup AS VARCHAR(100))+'-'+CAST(MIN(g.txt) AS VARCHAR(100))+' to '+
CAST(g.txtGroup AS VARCHAR(100))+'-'+CAST(MAX(g.txt) AS VARCHAR(100))
END
FROM
(
SELECT txtGroup = t1.txt, t2.txt, grouper = t2.txt - split.ItemNumber
FROM dbo.DelimitedSplit8K(REPLACE(@packagings,' ',''),',') AS split
CROSS APPLY (VALUES(CHARINDEX('-', split.item))) AS mid(pos)
CROSS APPLY (VALUES(SUBSTRING(split.item,1,mid.pos-1))) AS t1(txt)
CROSS APPLY (VALUES(SUBSTRING(split.item,mid.pos+1,8000))) AS t2(txt)
) g
GROUP BY g.txtGroup, g.grouper
ORDER BY g.txtGroup
FOR XML PATH('')
),1,2,'');
返回:
1-001 to 1-004, 1-007 to 1-008, 2-001