TSQL pivot a single column table -


sorry late response off few days, , not specifying exact table structure. please ignore previous description above. have more information original question not longer valid obtain more information regarding need described below:

i have following table (simplified version sake of discussion). first line headers:

variableid  documentid  revision  value 44          12          2         val1 45          12          2         val2 45          12          3         val3 44          13          1         val4 46          13          2         val5 47          14          1         val6 

i’d convert (assuming n number of rows) following grouped (documentid, revision) table:

documentid  revision  variable1 (44)  variable2 (45)  variable3(46)  variable(47)  variable (n) 12          2         val1            val2            null           null 12          3         null            val3            null           null 13          1         val4            null            null           null 13          2         null            null            val5           null 14          1         null            null            null           val6 

number of variable retrieved dynamically. not know how many variable in source table input.

please advise.

you did not provide lot of details current table structure or sample data. provide samples of pivot function perform this.

there 2 options pivot, static if know number of columns transform or dynamic list of columns @ run-time transform.

edit: based on change question, can still perform pivot

a static pivot (sql fiddle sample):

select *  (   select *   t ) x pivot  (   max(value)   variableid in([44], [45], [46], [47]) ) p 

as dynamic pivot looks (sql fiddle sample):

declare @cols nvarchar(max),     @query  nvarchar(max),     @colsalias nvarchar(max)  select @cols = stuff((select distinct ',' + quotename(variableid)                      t             xml path(''), type             ).value('.', 'nvarchar(max)')          ,1,1,'')  select @colsalias = stuff((select distinct ',' + quotename(m.variableid) + ' ' + quotename('variable' + cast(n.variableid varchar(10)))       t m inner join t n on m.variableid = n.variableid     xml path(''), type).value('.', 'nvarchar(max)'),1,1,'')   set @query = 'select documentid, revision, ' + @colsalias + '               (                 select *                 t             ) x             pivot              (                 max(value)                 variableid in (' + @cols + ')             ) p '  execute(@query) 

Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c++ - Using OpenSSL in a multi-threaded application -

All overlapping substrings matching a java regex -