在sql中格式化字符串

时间:2016-09-22 10:10:34

标签: sql

我输入为A1,A2,A3,A4,A7,A8,A9,D1,D2,D3

必需的输出应为A1-4,A7-9,D1-3

1 个答案:

答案 0 :(得分:1)

假设在数字字符之前总是有1个字母字符。

DECLARE @val NVARCHAR(100) = 'A1,A2,A3,A4,A7,A8,A9,D1,D2,D3'

;WITH CTE1
AS
(
    SELECT 1 AS Id, 0 AS Start, CAST('' AS NVARCHAR(100)) AS Result, CAST(@val + ',' AS NVARCHAR(100)) AS Val
    UNION ALL
    SELECT 
        Id + 1 AS Id,       
        CHARINDEX(',', val, C.Start) AS Start,      
        SUBSTRING(val, 0, CHARINDEX(',', val, C.Start)) AS Result,      
        SUBSTRING(val, CHARINDEX(',', val, C.Start) + 1, LEN(val)) AS Val
    FROM CTE1 C
    WHERE
        LEN(C.val) > 0
), CTE2
AS 
(
    SELECT 
        C.Id ,
        C.Start ,
        C.Result ,
        C.Val,
        RIGHT(C.Result, LEN(C.Result) -1 ) AS Num, 
        ROW_NUMBER() OVER (ORDER BY C.Result) AS RowId 
    FROM CTE1 C
    WHERE 
        C.Id  <> 1
), CTE3
AS
(
    SELECT MIN(C.Id) Id, MAX(C.Num) RowId 
    FROM CTE2 C
    GROUP BY Num - C.RowId
)

SELECT
STUFF
(
    (SELECT 
        ',' + A.Result + '-' + CAST(B.RowId AS NVARCHAR(10))
    FROM 
        CTE2 A INNER JOIN 
        CTE3 B ON A.Id = B.Id
    ORDER BY A.Result
    FOR XML PATH(''))
, 1, 1, '')

结果:A1-4,A7-9,D1-3