tsql - Converting Row to Column dynamically in SQL -
this question has answer here:
- t-sql dynamic pivot 5 answers
i have table below in microsoft sql server. want convert rows column.
my issue don't know result ahead , there can more 3 rows in result.
current table
id - function - result - masterkey 1 - 100 - 31 - 7 1 - 125 - 34 - 7 1 - 138 - 39 - 7 . - . - . - . . - . - . - .
desired result
masterkey - function1 - result1 - function2 - result2 - function3 - result3 - ... 7 - 100 - 31 - 125 - 34 - 138 - 39 - ...
how can achieve ? in advance.
you need create sql dynamically if have unknown number of functions/results:
declare @sql nvarchar(max) = ''; set @sql = 'select masterkey' + ( select ', function' + rownum + ' = max(case when rownumber = ' + rownum + ' [function] end)' + ', result' + rownum + ' = max(case when rownumber = ' + rownum + ' result end)' ( select distinct rownum = cast(row_number() on (partition masterkey order [function]) varchar(10)) t ) t xml path(''), type ).value('.', 'nvarchar(max)') + ' (select masterkey, [function], result, rownumber = row_number() on (partition masterkey order [function]) t) t group masterkey'; execute sp_executesql @sql;
Comments
Post a Comment