Quick Search for:  in language:    
Pivot,table,with,just,parameters,utility,desi
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
SQL Stats

 Code: 44,501. lines
 Jobs: 125. postings

 How to support the site

 
Sponsored by:

 
You are in:
 
Login





Latest Code Ticker for SQL
Beginners pack
By hardik shah on 1/11


Inline Views
By Thivya Prabakaran on 1/6


Create thousand Data Base users quickly
By N.D.I.Samantha on 1/1


Numbers from String
By Jeff Michelson on 12/30


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!

Affiliate Sites



 
 
   

Pivot Table via Parameters

Print
Email
 

Submitted on: 5/28/2003 4:51:28 PM
By: John Cappelletti  
Level: Advanced
User Rating: By 10 Users
Compatibility:SQL Server 2000, SQL Server 7.0

Users have accessed this article 5325 times.
 
 
     Pivot any table with just a few parameters. This utility was designed for adhoc analaysis and to serve as a workhorse. There is very little error trapping and would welcome any suggestions. Choose the Aggregate Function, i.e. Sum, Count, Avg, Min, Max, STD... Colums and rows may be expressions. Any valid filter may also be applied. When I don't want any filter, I simply set the expression to 1=1.


 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.

 

CREATE PROCEDURE spPivot_Table 
@cTable varchar(80),
@cDown varchar(80),
@cAcross varchar(80),
@cFuncvarchar(80),
@cAggFld varchar(80),
@cWhere varchar(200)
As

Drop Table TempUniq
Drop Table TempPivot

Declare @cColTtl varchar(80),
@cSQLStr varchar(200),
@cSQL varchar(8000),
@nRows Int,
@nCntr Int

-- Generate Pivot Key Table
Set @cSQL = 'Select Distinct '+@cAcross+' as Pivot_Value Into TempUniq From '+@cTable+' Where '+@cWHere+' Order By 1 '
Exec(@cSQL)
Select IDENTITY(int, 1,1) as Pivot_Row,@cFunc as Pivot_Func, @cAggFld as Pivot_AggFld,@cAcross as Pivot_Fld,@cColTtl as Pivot_Col,Pivot_Value,@cSQLStr as Pivot_SQL Into TempPivot From TempUniq Order By Pivot_Value

-- Generate Pivot_Col !! Need a Better T -- echnique for Safe Characters !!
Update TempPivot Set Pivot_Col = 'Col_'+Replace(RTrim(LTrim(Convert(varchar(80),Pivot_Value))),' ','_')

-- Build and Execute Pivot SQL
Update TempPivot Set Pivot_SQL=LTrim(RTrim(Pivot_Col))+'='+Pivot_Func+'(case when '+Pivot_Fld+'=Pivot_Value and Pivot_Col='''+Pivot_Col+''' Then '+Pivot_AggFld+' else Null end)'
Select @nRows=Max(Pivot_Row),@nCntr=Min(Pivot_Row) From TempPivot
Set @cSQL=''
While @nCntr <= @nRows
Begin
   Select @cSQL=@cSQL+','+Pivot_SQL From TempPivot Where Pivot_Row=@nCntr
   Set @nCntr=@nCntr+1
End

Set @cSQL='Select '+@cDown+','+Substring(@cSQL,2,8000)+' From '+@cTable+' Join TempPivot on('+@cAcross+'=Pivot_Value) Where '+@cWhere+' Group By '+@cDown+' Order By '+@cDown
Exec(@cSQL)

-- To Do
-- Add Logic for Col Names ie remove Spa -- ces, No Numerics, Nulls...
-- Add some error trapping
-- Add some logic for Destination 

-- Capabilities
-- Any Combination to "Down" or By Field -- s
-- Functions Available: Sum, Avg, Min, M -- ax, Count, STD, ...
-- Across may be an expression Substring -- (ShipCountry,1,1) = Across A,B,C,D,...-- r>
-- Samples
-- Exec spPivot_Table {Table},{By Fields -- },{Across Colums},{Agg Function},{Pivot -- Field},{Filer}
-- Exec spPivot_Table 'Orders','ShipCoun -- try','Year(OrderDate)','Sum','Freight',' -- 1=1'
-- Exec spPivot_Table 'Orders','ShipCoun -- try','Year(OrderDate)','Sum','Freight',' -- Year(OrderDate)>1996'
-- Exec spPivot_Table 'Orders','Employee -- ID,ShipCountry','Year(OrderDate)','Sum', -- 'Freight','1=1'
-- Exec spPivot_Table 'Orders','Employee -- ID,ShipCountry','Year(OrderDate)','Sum', -- 'Freight','1=1'
-- Exec spPivot_Table 'Orders','Employee -- ID,ShipCountry','Substring(ShipCountry,1 -- ,1)','Sum','Freight','1=1'


Other 3 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Advanced category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
8/21/2003 9:39:01 AM:Tom Bruinsma
in the code there is a missing space between the variable and the declaration @cFuncvarchar(80) should be @cFunc varchar(80)
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/21/2003 9:40:45 AM:Tom Bruinsma
ok, after i fixed that one, this is very cool! I have been looking for something to perform the task for a long time. This has the benefit of being very simplistic and easy to implement. I give you 5 globes. thanks for your contribution!
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/21/2003 9:58:46 AM:Tom Bruinsma
one last change I have automated scripts that display the results of a query sa is so i wanted the return to require little interaction -- Generate Pivot_Col !! Need a Better Technique for Safe Characters !! Update TempPivot Set Pivot_Col = '['+RTrim(LTrim(Convert(varchar(80),Pivo t_Value))) + ']'
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/29/2003 12:22:53 PM:
I have taken the liberty of adding code to create a TOTALS collumn to the end of the temp table... I am pasting the code below DECLARE @cTOTALStr varchar(2000) SET @cTOTALStr = ', TOTAL='+@cFunc+'(case when '+@cAcross+'=Pivot_Value Then '+@cAggFld +' else Null end)' SET @cSQL = @cSQL+@cTOTALStr this code goes at the end of teh while loop right after 'END'
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/9/2003 9:23:00 PM:
I have been working on a very large database application for some time in which I create the dynmaic sql for pivot tables frequently. This little pice of code saves me some serious time and effort so as I can concentrate on more important things, major kudos.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/2/2004 5:48:07 PM:
I'm not an SQL Master, but I was able to get this working and even add the 2 suggested enhancements. Works very well when all of the data needed for the pivot table is in one table. Any ideas on how to incorporate data from other tables?
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/4/2004 4:32:32 PM:John Cappelletti
I suspect any valid Join/Expression should work. If you have a complex query, it may be best to create a temp answer set, and the apply the pivot. Regrards...John Cappelletti
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | SQL Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.