Search this blog

Sunday, June 21, 2009

PIVOT Operator in SQL

PIVOT is a new T-SQL operator that you can specify in your FROM clause to rotate rows into columns and create a traditional crosstab query.

How to use Pivot:

In your SELECT statement, you specify the values you want to pivot on. The following example using the AdventureWorks database uses the order years (calculated using the DatePart function) as the columns. The FROM clause looks normal except for the PIVOT statement. This statement creates the value you want to show in the rows of the newly created columns. This example uses the aggregate SUM of TotalDue (a calculated field in the FROM clause). Then we use the FOR operator to list the values we want to pivot on in the OrderYear column. The example is shown here:

SELECT
CustomerID,
[2001] AS Y2001,
[2002] AS Y2002,
[2003] AS Y2003,
[2004] AS Y2004
FROM
(
SELECT CustomerID, DATEPART(yyyy, OrderDate) as OrderYear, TotalDue
FROM Sales.SalesOrderHeader
)piv
PIVOT
(

SUM (TotalDue)
FOR OrderYear IN
([2001], [2002], [2003],[2004])
)
AS chld
ORDER BY CustomerID

Output:

CustomerIDY2001Y2002Y2003Y2004
140732.606772366.1284NULLNULL
2NULL15653.671512118.02754962.2705
339752.8421168393.7021219434.426551925.3549
4NULL263025.3113373484.299143525.6018
5NULL33370.690160206.999920641.1106

More Rows .....

hope This example will help you to understand about concept of pivot operator

No comments:

Post a Comment