In this post, I explain how to write a simple PIVOT query in T-SQL and why we might want to use the PIVOT operator. The Oxford English Dictionary definition of PIVOT is
The central point, pin, or shaft on which a mechanism turns or oscillates.
So what we are doing here is TURNING THE DATA AROUND (PIVOTING) for visual purposes. The object of the exercise is to return 3 wide rows of data, instead of the 36 unique rows in the table.
Create the table and data which we will use in out PIVOT query
Lets create a database table which records the size of different tables within a database over time.
CREATE TABLE TableSize ( TableSizeId int identity (1,1) Primary Key, DatabaseName sysname, Name sysname, DataKB INT, Collection_Date Date )