How to Pivot Data in SQL Server

Sometimes it just makes sense to output a pivoted table, instead of purely columnar data, when running a T-SQL select query. It's easy to think of pivoting as a complex process when being implemented in code (as opposed to the visual environment of Excel for example), however it's actually quite simple once you get the basic premise. Here's a brief example:-

	month(date_value) as partition, -- This will determine the column headings
	field1 as grouping, -- This will determine the row headings
	field2 as value
	FROM database
	sum(value), FOR partition IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],

To make this work it's necessary to ensure that all of the possible 'partition' values (normally months or weeks etc.) are contained within the 'IN' part of the statement. Naturally you can perform any mathematical function on the 'value' in the pivot. Go on - try it.

Show Comments