/*----Create Table-----*/
CREATE TABLE[dbo].[PivotExample](
[City][nvarchar](50) NULL, [Year][smallint] NOT NULL, [SalesAmount][money] NULL)
GO
/*----Check Table is Created-----*/
select * from PivotExample;
/*----Insert Data in Table-----*/
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Delhi', 2005, 1309047.1978)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Mumbai', 2006, 521230.8475)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Kolkata', 2007, 2838512.3550)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Chennai', 2008, 922179.0400)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Delhi', 2007, 3033784.2131)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Chennai', 2005, 180571.6920)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Lucknow', 2006, 591586.8540)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Bareilly', 2006, 621602.3823)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Lucknow', 2005, 291590.5194)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Kolkata', 2005, 1100549.4498)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Bareilly', 2007, 535784.4624)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Chennai', 2007, 1026324.9692)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Mumbai', 2007, 1058405.7305)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Delhi', 2006, 2154284.8835)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Lucknow', 2008, 1210286.2700)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Kolkata', 2008, 3324031.1600)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Mumbai', 2008, 1076890.7700)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Lucknow', 2007, 1298248.5675)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Delhi', 2008, 2563884.2900)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Bareilly', 2005, 146829.8074)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Mumbai', 2005, 237784.9902)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Bareilly', 2008, 673628.2100)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Kolkata', 2006, 2126696.5460)
INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Chennai', 2006, 514942.0131)
GO
/*----Check Inserted Data in Table-----*/
Select * from PivotExample;
/*----Apply Pivoting-----*/
SELECT[City], [2005], [2006]
FROM[dbo].[PivotExample]
PIVOT(SUM(Sale) FOR[Year] IN([2005], [2006], [2007], [2008])) AS PThis code snippet for Converting row into column using excel function.
