Izenda, LLC

Ad Hoc Reports & Dashboards for ASP.NET Apps

Free Trial

Izenda Reports is licensed on a "per user" or "per server" basis. Please complete this form to receive a price quote.

All fields are required.

The live demo demonstrates Izenda reports with the Northwind Sample database. To login, please register below.

All fields are required.

Please register to try Izenda reports on your data today.

All fields are required.

How do I create a pivot table in Microsoft SQL ?

Expand / Collapse
 

How do I create a pivot table in Microsoft SQL ?


Pivots are a way to visual data in a more intuitive manner. If for instance, in your database, you have the ShipCountry, OrderDate and Freight cost. If you create a standard grid in SQL in order to get a total by year and country, your grid will look like this:
.--------------------------------------------------.
| Table without pivot |
+-------------+----------+-------------------------+
| ShipCountry | Freight | Group(Year)(Order Date) |
+-------------+----------+-------------------------+
| USA | $200.00 | 2005 |
| USA | $200.00 | 2006 |
| USA | $200.00 | 2007 |
| USA | $200.00 | 2008 |
| France | $100.00 | 2005 |
| France | $100.00 | 2006 |
| France | $100.00 | 2007 |
| France | $100.00 | 2008 |
+-------------+----------+-------------------------+
| | $1200.00 | |
'-------------+----------+-------------------------'
Although this gives us the information, it does not display it in an easy to consume way. So instead, we decide to pivot on the year, and turn the Order Date column into a column of the years and sum. In order to do this, we use this SQL code
SELECT [ShipCountry],SUM(Freight) AS Total,SUM(CASE DATEPART(yyyy,[OrderDate])
WHEN '2005' THEN Freight ELSE 0 END) AS [2005], SUM(CASE DATEPART(yyyy,[OrderDate])
WHEN '2006' THEN Freight ELSE 0 END) AS [2006], SUM(CASE DATEPART(yyyy,[OrderDate])
WHEN '2007' THEN Freight ELSE 0 END) AS [2007], SUM(CASE DATEPART(yyyy,[OrderDate])
WHEN '2008' THEN Freight ELSE 0 END) AS [2008]
FROM [Orders]
GROUP BY [ShipCountry]
This will result in columns being displayed in a much easier to read format:
.---------------------------------------------------------------.
| Pivoted Table |
+-------------+---------+---------+---------+---------+---------+
| ShipCountry | Total | 2005 | 2006 | 2007 | 2008 |
+-------------+---------+---------+---------+---------+---------+
| France | $400.00 | $100.00 | $100.00 | $100.00 | $100.00 |
| USA | $800.00 | $200.00 | $200.00 | $200.00 | $200.00 |
'-------------+---------+---------+---------+---------+---------'
Now the sum is across the columns instead of down the rows and is broken out individually by columns.



Details
Type: Fix
Options