DECLARE @t TABLE (Data VARCHAR(40)) INSERT @t (Data) SELECT '9992EDC6-D117-4DEE-B410-4E5FAE46AE97' INSERT @t (Data) SELECT '0BFC936B-BD9A-4C6A-AFB2-CF3F1752F8B1' INSERT @t (Data) SELECT '4A73E7EB-7777-4A04-9258-F1E75097977C' INSERT @t (Data) SELECT '5AAF477C-274D-400D-9067-035968F33B19' INSERT @t (Data) SELECT '725DA718-30D0-44A9-B36A-89F27CDFEEDE' INSERT @t (Data) SELECT '8083ED5A-D3B9-4694-BB04-F0B09C588888' ; --This solution requires a Numbers table. --Because I don't know if one is available, or if the user --that executes this query has permissions to master..spt_values, --one is being generated using cross joins and CTE's. WITH Z AS (SELECT 1 AS N UNION ALL SELECT 1), Y AS (SELECT A.N AS N FROM Z AS A CROSS JOIN Z AS B), X AS (SELECT A.N AS N FROM Y AS A CROSS JOIN Y AS B), Numbers AS ( SELECT ROW_NUMBER() OVER(ORDER BY A.N) AS N FROM X AS A CROSS JOIN Y AS B ) SELECT Data, [Char], MIN(Pos) AS Pos, COUNT(*) + 1 AS [Len] FROM ( SELECT T.Data, SUBSTRING(T.Data, N.N, 1) AS [Char], N.N AS Pos, --It is necesary a reference column for the cases when --a character forms different sequences in the same string. N.N - ROW_NUMBER() OVER(PARTITION BY DATA ORDER BY N.N) AS [Group] FROM @t AS T INNER JOIN Numbers AS N ON N.N <= LEN(T.Data) --If the current char and the next are the same, then a sequence exists AND SUBSTRING(T.Data, N.N, 1) = SUBSTRING(T.Data, N.N+1, 1) ) AS Seq GROUP BY Data, [Char], [Group] ORDER BY MAX(COUNT(*)) OVER(PARTITION BY Data) DESC, COUNT(COUNT(*)) OVER(PARTITION BY Data) DESC, Pos
Did you understand how this solution work? If you find it difficult to understand, you can Request an Explanation or you can Write an explanation to help others better understand this.