Попробуйте этот скрипт,
declare @flg int=3--test with 1,2,3,4 ...
create table #temp(id int identity(1,1),col varchar(10))
insert into #temp values ('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H')
create table #temp1(id int ,col varchar(10),flag int,rownum int)
declare @PvtCol varchar(500)=''
declare @Headcol varchar(500)
declare @Sql nvarchar(500)
WITH CTE
AS (SELECT id,
col,
CASE
WHEN(id % @flg) = 0
THEN @flg
ELSE(id % @flg)
END flag
FROM #temp),
CTE1
AS (SELECT *,
ROW_NUMBER() OVER(PARTITION BY flag
ORDER BY id) rownum
FROM cte)
INSERT INTO #temp1
(id,
col,
flag,
rownum
)
SELECT id,
col,
flag,
rownum
FROM cte1;
SELECT @PvtCol = COALESCE(@PvtCol + ', ' + QUOTENAME(rownum), QUOTENAME(rownum)),
@Headcol = COALESCE(@Headcol + ', ' + QUOTENAME(rownum) + ' as ' + 'col', QUOTENAME(rownum) + ' as ' + 'col') + CAST(rownum AS VARCHAR)
FROM #temp1
WHERE flag = 1;
SET @PvtCol = STUFF(@PvtCol, 1, 1, '');
SELECT @PvtCol,
@Headcol;
SET @Sql = 'select flag,' + @Headcol + ' from
(
select flag, col,rownum from #temp1
)src
pivot(max(col) for rownum in(' + @PvtCol + ')) as pvt';
PRINT @Sql;
EXECUTE sp_executesql
@Sql;
DROP TABLE #temp, #temp1;