; with cte as
(
select cast(replace(left(CompanyCase,9),'MH','') as int ) as value from Company where CompanyCase like '%MH%'
)
select max(value) - min(value) from cte
WITH nums
AS
(
SELECT LEFT(C.CompanyCase, 2) AS Code
,CAST(SUBSTRING(C.CompanyCase, X1.nStart, X2.nLen) AS int) AS num
FROM dbo.Company C
CROSS APPLY (VALUES(PATINDEX('%[0-9]%', CompanyCase))) X1 (nStart)
CROSS APPLY
(
VALUES
(
CASE
WHEN PATINDEX('%[^0-9]%', SUBSTRING(C.CompanyCase, X1.nStart, 255)) > 0
THEN PATINDEX('%[^0-9]%', SUBSTRING(C.CompanyCase, X1.nStart, 255)) - 1
ELSE 255
END
)
) X2 (nLen)
WHERE C.CompanyCase LIKE 'MH%'
)
,Gaps
AS
(
SELECT Code, num
,CASE
WHEN num + 1 = LAG(num) OVER (PARTITION BY Code ORDER BY num DESC)
THEN 0
ELSE 1
END AS Gap
FROM nums
)
,Grps
AS
(
SELECT Code, num
,SUM(Gap) OVER (PARTITION BY Code ORDER BY num DESC) AS Grp
FROM Gaps
)
SELECT Code
,MIN(num) AS MinNum
,MAX(num) AS MaxNum
FROM Grps
GROUP BY Code, Grp;
ps Trying to fill in missing gaps in a sequence is usually a bad idea. What happens if the missing number once existed and needs to be restored into the live dataset? etc.
Thanks. I only want the difference between the max MH value and min MH value of top 10 records? Is it possible to modify your query to achieve the same?
Are you talking about your code or Ifor's code? Your code is not handling al the patterns and failing. Ifor code works fine as it seems to be handling patterns.
i have changed my code .. now it picks up your patterns
; with cte as
(
select
replace(companycase,'MH ','') as Case1
from
Company where CompanyCase like 'MH %'
)
select
cast(left(case1,case when PATINDEX('%[^0-9]%',Case1)-1 = -1 then 5 else PATINDEX('%[^0-9]%',Case1)-1 end ) as int)
from
cte