PIVOT TABLE IN SQL

Introduction

This is a very simple example of Pivot query for the beginners. We use pivot queries when we need to transform data from row-level to columnar data.

Pivot query help us to generate an interactive table that quickly combines and compares large amounts of data. We can rotate its rows and columns to see different summaries of the source data, and we can display the details for areas of interest at a glance. It also help us to generate Multidimensional reporting.

Background

This post intends to help T-SQL developers get started with PIVOT queries. Most business applications will need some sort of PIVOT queries and I am sure many of you must have come across pivoting requirements several times in the past. 

Using the Code

Let us have a table name Invoice which has three properties, InvoiceNumberInvoiceDateInvoiceAmount. Suppose we have several rows input in the table. Our goal is to display the sum of InvoiceAmount each month.

 Collapse | Copy Code
SELECT * FROM (SELECT year(invoiceDate) as [year], left(datename(month,invoicedate),3)as [month], _  InvoiceAmount as Amount FROM Invoice) as InvoiceResult 

 Collapse | Copy Code
SELECT *  FROM (      SELECT           year(invoiceDate) as [year],left(datename(month,invoicedate),3)as [month],           InvoiceAmount as Amount       FROM Invoice  ) as s  PIVOT  (      SUM(Amount)      FOR [month] IN (jan, feb, mar, apr,       may, jun, jul, aug, sep, oct, nov, dec)  )AS pivot

Regards :
Vikram Singh Rana
Computer Science Engineer
9983384690

Comments

Popular posts from this blog

Generate a Report using Crystal Reports in Visual Studio 2010

SQL Server Database is enabled for Database Mirroring, but the database lacks quorum, and cannot be opened – Error 955

40 Cool Kitchen Gadgets For Food Lovers. I’d Love To Have #14!