How do I achieve this format using sql server query -
select * #table
gives me this
what want this.
how write query this? type of pivot?
you need dynamic pivot :
if(object_id('yourtable','u') not null) drop table yourtable create table yourtable (name varchar(100), value int) insert yourtable values ('a', 25), ('b', 30), ('a', 35), ('b', 40), ('a', 45) declare @columns varchar(1000), @columnas varchar(4000),@sql nvarchar(max) select @columns = stuff((select ',' + '[' + convert(varchar(30), number, 121) + ']' master..spt_values n n.number between 1 , (select top 1 count(*) yourtable group name order count(*) desc) , type = 'p' xml path('')), 1, 1, '') select @columnas = replace(@columns,'],[','] [value],[') + 'as [value]' set @sql = 'select [name],' + @columnas +' ( select *,row_number() over(partition name order value) [rn] yourtable ) tab pivot ( max([value]) rn in(' + @columns +') ) pvt' exec sp_executesql @sql
Comments
Post a Comment