Pivot Tables In SQL Server

First, let’s see the syntax for pivot tables.

  1. SELECT first_column AS <first_column_alias>,  
  2. [pivot_value1], [pivot_value2], ... [pivot_value_n]  
  3. FROM   
  4. (<source_table>) AS <source_table_alias>  
  5. PIVOT   
  6. (  
  7. aggregate function(<aggregate column>)  
  8. FOR <pivot column>  
  9. IN ([pivot_value1], [pivot_value2], ... [pivot_value_n])  
  10. AS <pivot_table_alias>;  
Parameters or Arguments

first_column

A column or expression that will display as the first column in the pivot table.

first_column_alias
The column heading for the first column in the pivot table.

pivot_value1, pivot_value2, ... pivot_value_n

A list of values to pivot.

source_table
A SELECT statement that provides the source data for the pivot table.

source_table_alias
An alias for the source_table.

aggregate_function
An aggregate function such as SUM, COUNT, MIN, MAX or AVG.

aggregate_column
The column or expression that will be used with the aggregate_function.

pivot_column
The column that contains the pivot values.

pivot_table_alias
An alias for the pivot table.

The PIVOT Clause can be used in 2005-2014 versions.

 

Ebook Download
View all
Learn
View all