If you find this article useful, consider making a small donation to show your support for this web site and its content.
Free app Developer Interview available here.

Available on the iPhone App Store
Available on the Google Play
AboutMe
About me:
Hi. My name is Farooq Kaiser and I'm a software developer from Toronto, Canada.



Using PIVOT and UNPIVOT with SQL 2005/2008

by Farooq Kaiser 31. May 2009 11:54

The PIVOT operator can be used to transform a set of rows into columns while the UNPIVOT operator complements the PIVOT operator by allowing you to turn columns into rows.

The following sample will use AdventureWorks database.

Sample Code

USE AdventureWorks
GO
SELECT DaysToManufacture, sum(StandardCost) AS Cost
FROM Production.Product
GROUP BY DaysToManufacture
Here is the result
DaysToManufacture  Cost
----------------- ---------------------
0                        1251.7851
1                        34477.5266
2                        2513.7578
4                       92092.823
SELECT 'Cost' AS Cost,
[0], [1], [2], [3], [4]
FROM
(SELECT DaysToManufacture, StandardCost
FROM Production.Product) AS Source
PIVOT
(
sum(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) AS P
Here is the result

Cost      0                     1                     2                     3                     4
---- --------------------- --------------------- --------------------- --------------------- ---------------------
Cost  1251.7851   34477.5266    2513.7578        NULL           92092.823

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

SQL


comments powered by Disqus

Comments

Jobs Autos Real estate Videos Power by Google