PIVOT in SQL SERVER 2008 with an example?

 Posted by CGN007 on 7/20/2012 | Category: Sql Server Interview questions | Views: 5101 | Points: 40
Answer:

PIVOT is a nonstandard relational operator that are supported by Transact-SQL. You can use it to manipulate a table-valued expression into another table. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output, and performs aggregations where they are required on any remaining column values that are wanted in the final output

Example
Input Table

VendorID EmployeeName Orders
--------------------------------------
1 Rahul 5
1 Sourav 3
1 Sunil 9
2 Rahul 8
2 Sourav 4
2 Sunil1 6

SELECT VendorID,[Rahul],[Sourav],[Sunil] 


FROM PurchaseOrder

PIVOT

( sum (Orders)FOR EmployeeName IN ([Rahul],[Sourav],[Sunil] )

) AS p



Output


VendorID Rahul Sourav Sunil
-------------------------------------
1 5 3 9
2 8 4 6


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response