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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 PIVOT

Author  Topic 

boosts
Starting Member

9 Posts

Posted - 2012-07-25 : 17:58:10
I have a table with the following format:

FeatureID | Spindle | Value
----------------------------
12345 | 1 | 2.454
12345 | 2 | 3.454
12345 | 3 | 4.454
98765 | 1 | 6.333
... | ... | ...

FeatureID and Spindle are both int and Value is float

Combination of FeatureID, Spindle is unique, however both FeatureID and Spindle can have repeated values in their respective columns.

I need to pivot this table into the following structure:

FeatureID | Spindle 1 | Spindle 2 | Spindle 3 | ...
----------------------------------------------------
12345 | 2.454 | 3.454 | 4.454 | ...
98765 | 6.333 | ... | ... | ...

The final catch is that I do not know how many Spindles are present, the pivot has to be dynamic. I have already taken a look at a few options using dynamic pivot but no luck.

Any help is appreciated.

yosiasz
Master Smack Fu Yak Hacker

1635 Posts

Posted - 2012-07-25 : 18:44:50
http://sqlblogcasts.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

is your answer from madhivan


EXEC dynamic_pivot
'SELECT FeatureID, value FROM boosts',
'''Spindle'' + cast(Spindle as varchar(50))',
'SUM(value)'

<><><><><><><><><><><><><><><><><>
If you don't have the passion to help people, you have no passion
Go to Top of Page

boosts
Starting Member

9 Posts

Posted - 2012-07-25 : 20:39:01
Worked great! thanks.
Go to Top of Page

yosiasz
Master Smack Fu Yak Hacker

1635 Posts

Posted - 2012-07-26 : 12:21:48
madhivanan is da man!

<><><><><><><><><><><><><><><><><>
If you don't have the passion to help people, you have no passion
Go to Top of Page
   

- Advertisement -