There is no need to search for the longest substring, so each substring with a length greater than 5 will always have a substring of 5 characters, which is a reference for counting. Therefore, we only need to check substrings of length 5.
The data samples have three rows that occur three times. _1114H , _1114 and 1114H ( _ should show the location of the space )
In this solution, master..spt_values used instead of a table of numbers.
declare @T table ( ID int identity, Data varchar(50) ) insert into @T values ('KDHFOUDHGOENWFIJ 1114H4363SDFHDHGFDG'), ('GSDLGJSLJSKJDFSG 1114H20SDGDSSFHGSLD'), ('SLSJDHLJKSSDJFKD 1114HJSDHFJKSDKFSGG') select top 1 substring(T.Data, N.Number, 5) as Word from @T as T cross apply (select N.Number from master..spt_values as N where N.type = 'P' and N.number between 1 and len(T.Data)-4) as N group by substring(T.Data, N.Number, 5) order by count(distinct id) desc
Result:
Word ------ 1114
source share