SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
Search:  
 
 

Simple Crosstab Procedure with Power

By cgruel, 2009/05/05

Total article views: 1379 | Views in the last 30 days: 91

UberCrossTab was created out of a need to create crosstab data as easily as MS Access does. It leverages SQL Server 2005's PIVOT function so it will NOT work in SQL Server 2000.

  • The only variables that are needed are the first 5.
  • It gets really interesting when you start using the others.
  • The "col" variables can reference another table allowing for a fully dynamic list of columns even if the data isnt in the pivot table.
  • Store the pivoted data into a table if desired.
  • Also you can use a select string in quotes as the pivot table, allowing for all kinds of joins.

So, if you had a table setup like...

Table1
ID Type Color
1 A RED
2 A RED
3 B RED
4 C BLUE
5 D GREEN

 

To get a crosstab showing Type as the rows and Color as the columns counting on ID you would use...

Note: The YOURDB reference is not needed if you stored the proc in the same database as your table.

EXECUTE [YOURDB].[dbo].[UberCrosstab]
@pivotRowFields = 'Type'
,@pivotField = 'Color'
,@pivotTable = '[YOURDB].[dbo].[Table1]'
,@aggField = 'ID'
,@aggFunc = 'COUNT'

 

Which returns...

 
TYPE RED BLUE GREEN
A 2 0 0
B 1 0 0
C 0 1 0
D 0 0 1

 

I hope this can be of use to some.

 

By cgruel, 2009/05/05

Total article views: 1379 | Views in the last 30 days: 91
Your response
 
 
Related tags

Crosstab     SQL Server 2005    
pivot     T-SQL    
Procedure    
 
 
Contribute

Free registration required...

To read the rest of this article, and access thousands of other articles, we ask you to register on the site and subscribe to our newsletters.

Login (existing users)

Login

Email:   Password:   Remember me: Forgotten your password?

Register (new users)

Register

Email:   Password:
Confirm:

Subscribing to our newsletters gets you:

  • ALL of our content (thousands of articles, scripts, and forum postings)
  • A daily newsletter (example)
  • A weekly news round up (example)
  • The opportunity to ask and answer questions in our forums
  • A daily Question of the Day to test and help you increase your knowledge of SQL Server.

Steve Jones
Editor, SQLServerCentral.com