Friday, October 21, 2005

robvolk has created a very useful MSSQL Stored Procedure that will generate a cross tab (pivot table in the Excel world) output. The SP takes four items as input:

  • a select statement (with group by)
  • a summary calculation (i.e.: SUM(), AVG(), MIN(), MAX(), etc.)
  • pivot column (or expression)
  • table name (or view)

Example Syntax (using the MSSQL sample "pubs" database):

EXECUTE crosstab 'select title from titles inner join sales on (sales.title_id=titles.title_id) group by title', 'sum(qty)','stor_id','stores'

Another item to add to his "Some things to look out for" section:

You need to be running this SP as System Administrator (sa). Adding a non-sa user with create database rights to the tempdb is insufficient since the user will be removed when the MSSQL server is recycled (as tempdb is re-created on recycle).