Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 dynamically adjust pivot table colums

Author  Topic 

SebJ
Starting Member

11 Posts

Posted - 2011-10-05 : 03:59:31
Hello!

I´ve got one question concerning pivot tables. How do I solve the following problem? I´d like to create a Pivot Table out of this (example):
ValueX | ValueY | link | k
12 | 49 | 12 | 4
12 | 49 | 13 | 43
12 | 49 | 13 | 33
14 | 87 | 13 | 54
23 | 47 | 14 | 23

Now, the link column should be converted as follows. The k values should be in the lines of the new columns:
ValueX | ValueY | 12 | 13 | 14
12 | 49 | 4 | 43 | 33
14 | 87 | - | 54 | -
23 | 47 | - | - | 23


I do know (somehow) about crafting a pivot table. What I don´t know is how to dynamically create these new columns (link). I don´t want to write like:

pivot (max(k) for link in ([12], [13], [14], … )

but something like:

pivot (max(k) for link in (“someTABLEnameWHEREallTHESElinksAREin”)

Then, I would be able to adjust my colums whenever I want to. Is this even possible? Did you get what I want!? I hope not to be too unprecise… THANKS FOR ANY HELP.

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2011-10-05 : 04:04:29
you will need to use Dynamic SQL to achieve this.

Refer to this link on Dynamic SQL. http://www.sommarskog.se/dynamic_sql.html

Also search this site for Dynamic Pivot


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-10-13 : 09:03:32
Also refer
http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -