SQL Server - Using the PIVOT operator



Summarizing sales data using PIVOT operator

declare @Sales table (
	salesRep nvarchar(10), 
	[Month] nvarchar(3), 
	[Sale]  int
)

insert into @Sales (salesRep , [Month] , [Sale])
select 'Rep1', 'Jan', 423 union all
select 'Rep1', 'Feb', 341 union all
select 'Rep1', 'Mar', 554 union all
select 'Rep1', 'Apr', 466 union all
select 'Rep1', 'May', 443 union all
select 'Rep2', 'Jan', 431 union all
select 'Rep2', 'Feb', 196 union all
select 'Rep2', 'Mar', 543 union all
select 'Rep2', 'Apr', 534 union all
select 'Rep2', 'May', 578 union all
select 'Rep3', 'Jan', 445 union all
select 'Rep3', 'Feb', 375 union all
select 'Rep3', 'Mar', 539 union all
select 'Rep3', 'Apr', 454 union all
select 'Rep3', 'May', 434 union all
select 'Rep4', 'Jan', 422 union all
select 'Rep4', 'Feb', 296 union all
select 'Rep4', 'Mar', 542 union all
select 'Rep4', 'Apr', 522 union all
select 'Rep4', 'May', 411 union all
select 'Rep5', 'Jan', 500 union all
select 'Rep5', 'Feb', 199 union all
select 'Rep5', 'Mar', 521 union all
select 'Rep5', 'Apr', 509 union all
select 'Rep5', 'May', 511  

SELECT [salesRep], [Jan], [Feb], [Mar], [Apr], [May]
FROM (
	SELECT 
		salesRep , 
		[Month] , 
		[Sale] 
	FROM @Sales 
) AS SourceTable
PIVOT
(
	max([Sale])
	FOR [Month] IN ([Jan], [Feb], [Mar], [Apr], [May])
) AS PivotTable

/*
Output:

salesRep Jan Feb Mar Apr May
-------- --- --- --- --- ---
Rep1     423 341 554 466 443
Rep2     431 196 543 534 578
Rep3     445 375 539 454 434
Rep4     422 296 542 522 411
Rep5     500 199 521 509 511
*/

Share |

 Cant find the page you are looking for?
 Help us to improve by adding the content that you are looking for.
 Leave a feedback
 We look forward to hear your comments and feedback.