Convert Row Into Column in SQL

  1. /*----Create Table-----*/  
  2. CREATE TABLE[dbo].[PivotExample](  
  3.     [City][nvarchar](50) NULL, [Year][smallintNOT NULL, [SalesAmount][money] NULL)  
  4. GO  
  5. /*----Check Table is Created-----*/  
  6. select * from PivotExample;  
  7. /*----Insert Data in Table-----*/  
  8. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Delhi', 2005, 1309047.1978)  
  9. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Mumbai', 2006, 521230.8475)  
  10. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Kolkata', 2007, 2838512.3550)  
  11. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Chennai', 2008, 922179.0400)  
  12. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Delhi', 2007, 3033784.2131)  
  13. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Chennai', 2005, 180571.6920)  
  14. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Lucknow', 2006, 591586.8540)  
  15. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Bareilly', 2006, 621602.3823)  
  16. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Lucknow', 2005, 291590.5194)  
  17. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Kolkata', 2005, 1100549.4498)  
  18. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Bareilly', 2007, 535784.4624)  
  19. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Chennai', 2007, 1026324.9692)  
  20. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Mumbai', 2007, 1058405.7305)  
  21. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Delhi', 2006, 2154284.8835)  
  22. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Lucknow', 2008, 1210286.2700)  
  23. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Kolkata', 2008, 3324031.1600)  
  24. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Mumbai', 2008, 1076890.7700)  
  25. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Lucknow', 2007, 1298248.5675)  
  26. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Delhi', 2008, 2563884.2900)  
  27. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Bareilly', 2005, 146829.8074)  
  28. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Mumbai', 2005, 237784.9902)  
  29. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Bareilly', 2008, 673628.2100)  
  30. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Kolkata', 2006, 2126696.5460)  
  31. INSERT[dbo].[PivotExample]([City], [Year], [Sale]) VALUES(N 'Chennai', 2006, 514942.0131)  
  32. GO  
  33. /*----Check Inserted Data in Table-----*/  
  34. Select * from PivotExample;  
  35. /*----Apply Pivoting-----*/  
  36. SELECT[City], [2005], [2006]  
  37. FROM[dbo].[PivotExample]  
  38. PIVOT(SUM(Sale) FOR[YearIN([2005], [2006], [2007], [2008])) AS P