Tuesday, March 18, 2014

Simple way to convert Rows to Columns dynamically in SQL Server using PIVOT keyword

Here I will explain how to convert Rows to Columns dynamically in SQL server using PIVOT keyword.This is a very simple example of Pivot query for the beginners.

Pivot keyword in sql query help us to generate table that quickly combines and compares large amounts of data.We can convert its rows and columns to see different summaries of the source data.Pivot keyword also help us to create Multidimensional reporting.


Database

 For this example I have created a database named InvoiceDB which has a table named tbl_invoice    with the schema as follows.










In the tbl_invoice Table I have inserted few records as shown below




























SELECT * FROM 
(
SELECT Invoice_Year,Invoice_Month,Invoice_Amount
FROM 
tbl_invoice
)
as s PIVOT 
(  
SUM(Invoice_Amount)
 FOR [Invoice_Month] IN (jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec)
)AS s




No comments:

Post a Comment