T-SQL Tutorials - TSQLTutorials.com

UNPIVOT Statement


Introduction

The UNPIVOT statement is used for changing columns into rows in a SQL Query (Normalization). The UNPIVOT Statement is generally written in this form:

  • SELECT
      [DataType]
    ,   [DataValue]
    ,   [UnpivotedCol1]
    ,   [UnpivotedCol2]
    ,   [UnpivotedCol3]
  • FROM table
  • UNPIVOT
    (
      [DataValue] FOR [DataType]
      IN ([UnpivotedCol1],[UnpivotedCol1],[UnpivotedCol3],etc..)
    )
    AS Alias
Note: You must use brackets around each of the Pivot Column Values


Beginning Example - Example #1

Download This Script
This example will use the following table: SELECT Country, Sales, Expenses, Taxes, Profit
FROM #table1234
Here is a resultset from the above SELECT query:

Country Sales Expenses Taxes Profit
Asia 800000 350000 100000 NULL
Eupore 25000001250000 500000 750000
North America 2000000250000 250000 500000
South America 500000 250000 NULL NULL

Now we can use the UNPIVOT Keyword to normalize the result. This will turn the columns of Sales, Expenses, Taxes and Profit into Rows. Each column will become a row from the existing row. A Single row be created for each column, for each country.

SELECT Country, Amount.Amount, Amount.AmountType
FROM #table1234
  UNPIVOT (Amount for AmountType in (Sales, Expenses,Taxes,Profit)) as Amount
Here is a resultset from the above UNPIVOT query:

Country Amount AmountType
Asia 800000 Sales
Asia 350000 Expenses
Asia 100000 Taxes
Europe 2500000 Sales
Europe 1250000 Expenses
Europe 500000 Taxes
Europe 750000 Profit
North America 2000000 Sales
North America 250000 Expenses
North America 250000 Taxes
North America 500000 Profit
South America 500000 Sales
South America 250000 Expenses

If for the above example, we just want the Sales and Expenses rows for each country, then we can use this query:

SELECT Country, Amount.Amount, Amount.AmountType
FROM #table1234
  UNPIVOT (Amount for AmountType in (Sales, Expenses)) as Amount
Here is a resultset from the above UNPIVOT query:

Country Amount AmountType
Asia 800000 Sales
Asia 350000 Expenses
Europe 2500000 Sales
Europe 1250000 Expenses
North America 2000000 Sales
North America 250000 Expenses
South America 500000 Sales
South America 250000 Expenses



Microsoft SQL Server Standard 2008 R2 10CAL 228-09180

Price: $2040
Buy It Now
SQL Server 2008 2005 Training Exam Test Developer DVD Enterprise Book mcts 5cal

Current Price: $16.99
Current Bids: 0
★ NEW ★ MS SQL 2005 Server Standard with CAL ★ L@@K PRICE REDUCTION★

Price: $395
Buy It Now
Microsoft SQL Server 2008 - Enterprise with 25 CAL's

Price: $13850
Buy It Now
228-04023 Microsoft SQL Server 2005 Standard 5 CAL

Price: $1450
Buy It Now
Microsoft SQL Server 2005 Workgroup Edition 5 CAL, New Retail, PN A5K-01017

Price: $699.95
Buy It Now







Copyright 2012 - TSQLTutorials.com