What this allows you to do is to turn query results on their side, so instead of having results listed down like the listing below,
you have results listed across.
| SalesPerson | Product | SalesAmount |
| Bob | Pickles | $100.00 |
| Sue | Oranges | $50.00 |
| Bob | Pickles | $25.00 |
| Bob | Oranges | $300.00 |
| Sue | Oranges | $500.00 |
| SalesPerson | Oranges | Pickles |
| Bob | $300.00 | $125.00 |
| Sue | $550.00 |
First you have the data rows, such as SalesPerson and the columns,
such as the Products and then the values to display for each cross section.
Here is a simple query that allows us to pull the cross-tab results.
FROM
(SELECT SalesPerson, Product, SalesAmount
FROM ProductSales ) ps
PIVOT
(
SUM (SalesAmount)
FOR Product IN
( [Oranges], [Pickles])
) AS pvt
- (1) The SELECT statement
- SELECT SalesPerson, [Oranges] AS Oranges, [Pickles] AS Pickles
- This portion of the query selects the three columns for the final result set (SalesPerson, Oranges, Pickles)
- (2) The query that pulls the raw data to be prepared
- (SELECT SalesPerson, Product, SalesAmount FROM ProductSales) ps
- This query pulls all the rows of data that we need to create the cross-tab results. The (ps) after the query is creating a temporary table of the results that can then be used to satisfy the query for step 1.
- (3) The PIVOT expression
- PIVOT (SUM (SalesAmount) FOR Product IN ( [Oranges], [Pickles]) ) AS pvt
- This query does the actual summarization and puts the results into a temporary table called pvt
refrence:http://www.mssqltips.com

