CREATETABLE #temp(name NVARCHAR(50),colValue INT ) INSERTINTO #tempSELECTLEFT(col,6) AS name ,SUBSTRING(col,7,LEN(col)) FROM #tempsource
?將數據進行排序分組
select v1.colValue, (v1.colValue - v1.rownum) as delta ,v1.name INTO #tempSortfrom (select Row_Number() OVER (ORDERBY name,colValue) as rownum,colValue ,namefrom #temp ) v1
找出連續的數字并分組?
SELECT v2.name,delta,MIN(v2.colValue) as StartNum, max(v2.colValue) as EndNum,
max(v2.colValue)-min(v2.colValue)+1asCount,ROW_NUMBER() OVER( ORDERBY v2.delta ASC ) AS rownum
INTO #tempContinuity
from #tempSort v2
--WHERE v2.colValue >=2groupby v2.name,v2.deltaORDERBY StartNum
跟據連續的信息找出不連續的數字并分組
SELECT tlx1.name,tlx1.EndNum+1 LostStartNum,tlx2.StartNum-1AS LostEndNum,tlx2.StartNum-1-(tlx1.EndNum+1)+1 LostCount
INTO #tempLost
FROM #tempContinuity AS tlx1
LEFTJOIN #tempContinuity AS tlx2 ON tlx1.rownum+1= tlx2.rownum AND tlx2.name = tlx1.name
WHERE tlx2.StartNum ISNOTNULLORDERBY tlx1.delta
將取得的信息進行組裝成源格式進行顯示
SELECT name +RIGHT('0000000'+CAST(StartNum ASNVARCHAR),5) AS StartNum ,name +RIGHT('0000000'+CAST(EndNum ASNVARCHAR),5) AS EndNum,CountFROM #tempContinuity
SELECT name +RIGHT('0000000'+CAST(LostStartNum ASNVARCHAR),5) AS LostStartNum ,name +RIGHT('0000000'+CAST(LostEndNum ASNVARCHAR),5) AS LostEndNum,LostCount FROM #tempLost
?
使用ForXml將其分組合并成一行
SELECT name,STUFF((SELECT name +RIGHT('0000000'+CAST(StartNum ASNVARCHAR),5) +'-'+name +RIGHT('0000000'+CAST(EndNum ASNVARCHAR),5)+'|'+CAST(t.CountASNVARCHAR) +';'FROM #tempContinuity AS t WHERE t.name =v.name FOR XML PATH ('')),1,0,'') AS strCardFROM #tempContinuity AS vGROUPBY v.name