What is pivot operator in SQL Server?

Pivot is a sql server operator that can be used to turn unique values from one column, into multiple columns in the output, there by effectively rotating a table

Create Table tblProductSales
(
 SalesAgent nvarchar(50),
 SalesCountry nvarchar(50),
 SalesAmount int 
)

Insert into tblProductSales values('Tom', 'UK', 200)
Insert into tblProductSales values('John', 'US', 180)
Insert into tblProductSales values('John', 'UK', 260)
Insert into tblProductSales values('David', 'India', 450)
Insert into tblProductSales values('Tom', 'India', 350)
Insert into tblProductSales values('David', 'US', 200)
Insert into tblProductSales values('Tom', 'US', 130)
Insert into tblProductSales values('John', 'India', 540)
Insert into tblProductSales values('John', 'UK', 120)
Insert into tblProductSales values('David', 'UK', 220)
Insert into tblProductSales values('John', 'UK', 420)
Insert into tblProductSales values('David', 'US', 320)
Insert into tblProductSales values('Tom', 'US', 340)
Insert into tblProductSales values('Tom', 'UK', 660)
Insert into tblProductSales values('John', 'India', 430)
Insert into tblProductSales values('David', 'India', 230)
Insert into tblProductSales values('David', 'India', 280)
Insert into tblProductSales values('Tom', 'UK', 480)
Insert into tblProductSales values('John', 'US', 360)
Insert into tblProductSales values('David', 'UK', 140) 



Select * from tblProductSales


SalesAgent  
SalesCountry  
SalesAmount
Tom
UK
200
John
US
180
John
UK
260
David
India
450
Tom
India
350
David
US
200
Tom
US
130
John
India
540
John
UK
120
David
UK
220
John
UK
420
David
US
320
Tom
US
340
Tom
UK
660
John
India
430
David
India
230
David
India
280
Tom
UK
480
John
US
360
David
UK
140



Now, let's write a query which returns TOTAL SALES, grouped by SALESCOUNTRY and SALESAGENT. The output should be as shown below. 


SalesCountry
SalesAgent
Total
India
David
960
India
John
970
India
Tom
350
UK
David
360
UK
John
800
UK
Tom
1340
US
David
520
US
John
540
US
Tom
470


A simple GROUP BY query can produce this output.
Select SalesCountry, SalesAgent, SUM(SalesAmount) as Total
from tblProductSales
group by SalesCountry, SalesAgent
order by SalesCountry, SalesAgent



At, this point, let's try to present the same data in different format using PIVOT operator. 



SalesAgent
India
US
UK
David
960
520
360
John
970
540
800
Tom
350
470
1340


Select SalesAgent, India, US, UK
from tblProductSales
Pivot
(

   Sum(SalesAmount) for SalesCountry in ([India],[US],[UK])
as PivotTable

No comments:

Post a Comment

What is Normalization?

Database normalization is a data design and organization process applied to data structures based on rules that help building relational dat...