I have a Table shown below
DateRange
10/1
11/1
12/1
I am looping through this table using cursor and trying to populate a temp table
Use PIVOT as
SELECT Code,
[22] Data1,
[33] Data2,
[43] Data3
FROM
(
SELECT *
FROM T
) TBL
PIVOT
(
MAX(Data) FOR Data IN([22],[33],[43])
) PVT
Demo
For dynamic pivot
CREATE TABLE T
(
Code VARCHAR(45),
Data INT
);
INSERT INTO T VALUES
('SL Payroll', 22),
('SL Payroll', 33),
('SL Payroll', 43);
DECLARE @IN VARCHAR(MAX) = '',
@Cols VARCHAR(MAX) = '';
SELECT @IN = @IN + ',' + QUOTENAME(Data),
@Cols = @Cols + ',' + QUOTENAME(Data) + ' AS Data'+
CAST(ROW_NUMBER()OVER(ORDER BY (SELECT NULL)) AS VARCHAR)
FROM T;
SELECT @IN = STUFF(@IN, 1, 1, ''), @Cols = STUFF(@Cols, 1, 1, '');
DECLARE @SQL NVARCHAR(MAX) = N'SELECT Code, ' +
@Cols+
' FROM (SELECT * FROM T) TBL PIVOT (MAX(Data) FOR Data IN('+
@IN+
')) PVT';
EXECUTE sp_executesql @SQL;
Demo