关于统计 表 一个字段 中连续出现相同数据的一个算法
需求:
有一个表 一个字段的数值如 10,2,30,30,30,4,4,5,5,6,7,77,7,7,7,7,7,8,8,8,8,8,9,9,10,10,10
现在要将字段中相邻且相同的数据统计出来,只出现一次记为1,出现2记为2,如上面的字段统计的结果为 1,1,3,2,2,1,1,1,5,5,2,3其第一个1代表10连续出现一次,第二个1代表2连续出现一次,3代表30连续出现三次,以次类推
我想请教高手,这个怎么做比较好,谢谢啦,在线等待中!!!!!
------解决方案--------------------Create Table A
(ID Int)
Insert A Select 10
Union All Select 2
Union All Select 30
Union All Select 30
Union All Select 30
Union All Select 4
Union All Select 4
Union All Select 5
Union All Select 5
Union All Select 6
Union All Select 7
Union All Select 77
Union All Select 7
Union All Select 7
Union All Select 7
Union All Select 7
Union All Select 7
Union All Select 8
Union All Select 8
Union All Select 8
Union All Select 8
Union All Select 8
Union All Select 9
Union All Select 9
Union All Select 10
Union All Select 10
Union All Select 10
GO
Select OrderID = Identity(Int, 1, 1), * Into #T From A
Select
IsNull((Select Min(OrderID) From #T Where ID != A.ID And OrderID > A.OrderID), (Select Max(OrderID) From #T) + 1) - A.OrderID As [Count]
From #T A
Where Exists (Select OrderID From #T Where ID != A.ID And OrderID = A.OrderID - 1)
Or A.OrderID = 1
Drop Table #T
GO
Drop Table A
--Result
/*
Count
1
1
3
2
2
1
1
1
5
5
2
3
*/