SQL Server - Using the UNPIVOT Operator



Spreading out the sales data using UNPIVOT operator

declare @Sales  table(
	salesRep nvarchar(10), 
	Jan int, Feb int, Mar int
);

INSERT INTO @Sales  VALUES ( 'Rep1', 423,  341,  554);
INSERT INTO @Sales  VALUES ( 'Rep2', 431,  196,  543);

-- sample data
SELECT * FROM @Sales 
/*
salesRep   Jan         Feb         Mar
---------- ----------- ----------- -----------
Rep1       423         341         554
Rep2       431         196         543
*/

--Unpivot the table.
SELECT  salesRep, [Month], Sale
FROM (
	SELECT salesRep, Jan, Feb, Mar
	FROM @Sales ) p
UNPIVOT (
	Sale FOR [Month] IN ([Jan], [Feb], [Mar])
)AS unpvt ;

/*
output:
salesRep   Month Sale  
---------- ----- ------
Rep1       Jan   423
Rep1       Feb   341
Rep1       Mar   554
Rep2       Jan   431
Rep2       Feb   196
Rep2       Mar   543
*/

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.