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
 Simple PIVOT Question

Author  Topic 

funk.phenomena
Posting Yak Master

121 Posts

Posted - 2012-07-25 : 13:41:55
Hi All! I have a simple sales table that looks like this:
[CODE]
ORDER_NUM SKU MONTH

50412355 T300 1
50412356 T300 1
50412357 T310 2
50412358 R310 4
50412359 Z566 2
[/CODE]
I'm using the PIVOT function to pivot the table:

[CODE]
SELECT * FROM
(SELECT [SKU], [MONTH] FROM SALES_TABLE) AS T1
PIVOT
(COUNT([MONTH]) FOR [MONTH] IN ([1], [2], [3], [4], [5], [6], [7])

) AS P1
[/CODE]

Suppose there's hundreds of unique values within the Month column.
Is there a way to write the code so that I don't have to specify ALL the values within the month. [CODE] FOR MONTH IN ([[1], [2] ... [/CODE]

Instead, it can do something like [CODE] FOR MONTH IN (*)[/CODE] ?
Thanks!


visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-07-25 : 14:00:13
nope..you've to use dynamic sql for that

http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-07-25 : 14:00:20
Nothing that I know of exists natively that would let you do this. The only alternatives I can think of are:

a) Go full-blown dynamic SQL. So you would construct your pivot query dynamically (but still would explicitly list the columns as individual items in the query string).

b) Use dynamic pivoting such as described in Madhivanan's blog: http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx
Go to Top of Page
   

- Advertisement -