Это ответ, который вы ищете:
create Table [table] (RowID int, RowCode char(1), RowValue int)
INSERT [Table] VALUES ( 6,'A',3757 )
INSERT [Table] VALUES ( 5,'A',37827)
INSERT [Table] VALUES (14,'A',48411)
INSERT [Table] VALUES ( 1,'A',48386)
INSERT [Table] VALUES (20,'A',48450)
INSERT [Table] VALUES ( 7,'A',46155)
INSERT [Table] VALUES (13,'A',721 )
INSERT [Table] VALUES ( 2,'A',49335)
INSERT [Table] VALUES (15,'A',4700 )
INSERT [Table] VALUES (19,'A',64416)
INSERT [Table] VALUES ( 8,'A',27246)
INSERT [Table] VALUES (12,'B',54929)
INSERT [Table] VALUES (16,'B',3872 )
INSERT [Table] VALUES ( 3,'C',728 )
INSERT [Table] VALUES (11,'C',1050 )
INSERT [Table] VALUES ( 9,'C',3191 )
INSERT [Table] VALUES (17,'C',866 )
INSERT [Table] VALUES ( 4,'C',838 )
INSERT [Table] VALUES (10,'D',550 )
INSERT [Table] VALUES (18,'D',1434 )
IF object_id('tempdb..#tempTable') IS NOT NULL
BEGIN
DROP TABLE #tempTable
END
CREATE TABLE #tempTable
(RowID int, RowCode char(1), RowValue int,RowChunk int)
INSERT INTO #tempTable
select RowID,RowCode,RowValue,null from [table]
declare @RowId int
declare @RowCode char(1)
declare @Count int
declare @CurrentCode char(1)
declare @CountCurrent int
set @Count=1
set @CurrentCode=1
set @CountCurrent=0
DECLARE contact_cursor CURSOR FOR
SELECT RowID,RowCode FROM [table]
OPEN contact_cursor
FETCH NEXT FROM contact_cursor into @RowId,@RowCode
set @CurrentCode=@RowCode
WHILE @@FETCH_STATUS = 0
BEGIN
if(@CurrentCode=@RowCode)
begin
if(@CountCurrent=5)
begin
set @CountCurrent=1
set @Count=@Count+1
update #tempTable set RowChunk=@Count where RowID=@RowID
end
else
begin
set @CountCurrent=@CountCurrent+1
update #tempTable set RowChunk=@Count where RowID=@RowID
end
end
else
begin
set @CurrentCode=@RowCode
set @CountCurrent=1
set @Count=@Count+1
update #tempTable set RowChunk=@Count where RowID=@RowID
end
FETCH NEXT FROM contact_cursor into @RowId,@RowCode
END
CLOSE contact_cursor
DEALLOCATE contact_cursor
select * from #tempTable
GO