SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Simple PIVOT Question
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

funk.phenomena
Yak Posting Veteran

Canada
98 Posts

Posted - 07/25/2012 :  13:41:55  Show Profile  Reply with Quote
Hi All! I have a simple sales table that looks like this:

ORDER_NUM SKU MONTH

50412355 T300 1
50412356 T300 1
50412357 T310 2
50412358 R310 4
50412359 Z566 2

I'm using the PIVOT function to pivot the table:


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


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.
FOR MONTH IN ([[1], [2] ...


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



Edited by - funk.phenomena on 07/25/2012 13:52:25

visakh16
Very Important crosS Applying yaK Herder

India
48012 Posts

Posted - 07/25/2012 :  14:00:13  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 07/25/2012 :  14:00:20  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000