sql - Dynamic Pivot Not displaying right output -


i have table:

year month| user| player  | manager 1996-06   | 1256|  2      |   1 1997-07   | 1243|  5      |   2 

and trying pivot returns:

       | 1997-06|1996-07 user   | 1256   | 1243 player | 2      |   5 manager| 1      |   2 

however i'm not sure why script below returning different:

declare @columns nvarchar(max), @sql nvarchar(max); set @columns = n''; select @columns += n', p.' + quotename([user])    (select p.[user] dbo.practise p   group p.[user]) x; set @sql = n' select ' + stuff(@columns, 1, 2, '') + ' (   select [year month], [user]    dbo.practise p  ) j pivot (   sum([user]) [year month] in ('   + stuff(replace(@columns, ', p.[', ',['), 1, 1, '')   + ') ) p;'; print @sql; exec sp_executesql @sql; 

it returns:

    1256|1243 1   null|null 

not sure i'm doing wrong :/

your simplify bit

example

declare @sql varchar(max) = ' select *   (         select [year month]               ,b.*          practise          cross apply (values (''user''   ,cast([user]  varchar(max)))                             ,(''player'' ,cast(player  varchar(max)))                             ,(''manager'',cast(manager varchar(max)))                      ) b (item,value)         )  pivot (max([value]) [year month] in (' + stuff((select distinct ','+quotename([year month])                                                        practise                                                       order 1                                                        xml path('')),1,1,'')  + ') ) p  order 1 desc' exec(@sql); --print @sql 

returns

item    1996-06   1997-07 user    1256      1243 player  2         5 manager 1         2 

the generated sql looks this

select *   (         select [year month]               ,b.*          practise          cross apply (values ('user'   ,cast([user]  varchar(max)))                             ,('player' ,cast(player  varchar(max)))                             ,('manager',cast(manager varchar(max)))                      ) b (item,value)         )  pivot (max([value]) [year month] in ([1996-06],[1997-07]) ) p  order 1 desc 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -