我有数字和数字和字符的组合,但没有序列。如果这些是顺序的,那么结果应如下所示。如果我有像这样的数据 下面。 值为C 1,C 2,C 5,C 7,T 1,T 5,T 6,T 55
需要结果如 C 1 -C 2,C 5,C 7,T 1,T 5 -T 6,T 55
字符后没有空格。
答案 0 :(得分:1)
您可以使用以下SQL语句:
SELECT
STUFF( (SELECT ',' + CAST(FNAME AS VARCHAR(MAX))
FROM OldTable
ORDER BY LNAME desc
FOR XML PATH('')),
1, 1, '')
以下是wewesthemenace提供的查询的更新版本:
WITH CteSplit(letter, number) AS(
SELECT
LTRIM(RTRIM(LEFT(FNAME, PATINDEX('%[0-9]%', FNAME) -1))),
CAST(RIGHT(FNAME, LEN(FNAME) - PATINDEX('%[0-9]%', FNAME) + 1) AS INT)
FROM OldTable
)
,Cte AS(
SELECT *,
RN = number - ROW_NUMBER() OVER(PARTITION BY letter ORDER BY number)
FROM CteSplit
)
,CteFinal AS(
SELECT
letter,
startNumber = MIN(number),
endNumber = MAX(number)
FROM Cte
GROUP BY letter, RN
)
SELECT
STUFF((
SELECT ',' + letter + ' ' + CAST(startNumber AS VARCHAR(MAX)) +
CASE
WHEN startNumber = endNumber
THEN ''
ELSE
'-' + letter + ' ' + CAST(endNumber AS VARCHAR(MAX))
END
FROM CteFinal
ORDER BY letter, startNumber, endNumber
FOR XML PATH('')
)
,1, 1, '')
升级: