To pivot data you need something to pivot it by.
In this case it can be generated using ROW_NUMBER.
For example:
--
-- sample data
--
create table yourlargetable (
id int identity(1,1) primary key,
name nvarchar(30),
value nvarchar(30)
);
insert into yourlargetable (name, value) values
('jane', 'val1'), ('jane', 'val2'), ('jane', 'val3'),
('john', 'val4'), ('john', 'val5');
--
-- declare a few variables
--
declare @DynSql nvarchar(max);
declare @Cols nvarchar(max);
declare @ColTotal int;
--
-- how many columns are needed
--
select top 1 @ColTotal = count(*)
from yourlargetable
group by name
order by count(*) desc;
--
-- generate a string with column names
--
with RCTE_NUMS as
(
select 1 as n
union all
select n+1
from RCTE_NUMS
where n < @ColTotal
)
select @Cols = concat(@Cols+', ', quotename(concat('Value', n)))
from RCTE_NUMS
order by n;
--
-- create the dynamic sql string
--
set @DynSql = 'select *'+ char(10) +
'from ('+
'select name, value '+ char(10) +
', concat(''Value'', row_number() over (partition by name order by value)) col '+ char(10) +
'from yourlargetable) s'+ char(10) +
'pivot (max(value) '+ char(10) +
'for col in ('+ @Cols +')) p'+ char(10) +
'order by name';
-- select @DynSql;
--
-- run the dynamic sql
--
exec sp_executesql @DynSql;
Returns:
name Value1 Value2 Value3
jane val1 val2 val3
john val4 val5 NULL