sql server - T-SQL dynamic pivot -


ok have table looks this

itemid | columnname | value 1      | name       | peter 1      | phone      | 12345678 1      | email      | peter@host.com 2      | name       | john 2      | phone      | 87654321 2      | email      | john@host.com 3      | name       | sarah 3      | phone      | 55667788 3      | email      | sarah@host.com 

now need turn this:

itemid | name  | phone    | email 1      | peter | 12345678 | peter@host.com 2      | john  | 87654321 | john@host.com 3      | sarah | 55667788 | sarah@host.com 

i have been looking @ dynamic pivot examples, seems im not able fit them scenario.

can help?

have @ following example

create table #table (         id int,         columnname varchar(250),         value varchar(250) )  insert #table select 1,'name','peter'  insert #table select 1,'phone','12345678'  insert #table select 1,'email','peter@host.com'  insert #table select 2,'name','john'  insert #table select 2,'phone','87654321'  insert #table select 2,'email','john@host.com'  insert #table select 3,'name','sarah'  insert #table select 3,'phone','55667788'  insert #table select 3,'email','sarah@host.com'   ---i assumed tablename testtable---  declare @cols nvarchar(2000)  declare @query nvarchar(4000)   select  @cols = stuff(( select distinct top 100 percent                                  '],[' + t.columnname                             #table t                          --order '],[' + t.id                          xml path('')                        ), 1, 2, '') + ']'   select  @cols  set @query = n'select id,'+ @cols +'  (select t1.id,t1.columnname , t1.value #table t1) p  pivot (max([value]) columnname in ( '+ @cols +' ))  pvt;'   execute(@query)  drop table #table 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -