Pivot tables in sqlserver 2008


In this article we are going to see what is a PIVOT table. What are the advantages of using a pivot table. A Pivot Table is a Table which can count and total the data stored in a column and use it to create a second table which displays the summarized data. The PIVOT keyword in sqlserver displays the values of a specified column as column name.

In this article we are going to see what is a PIVOT table. What are the advantages of using a pivot table.
A Pivot Table is a Table which can count and total the data stored in a column and use it to create a second table which displays the summarized data. The PIVOT keyword in sqlserver displays the values of a specified column as column name.
Let us see an example below:

1.First create a table student with follwing columns:StudentName,Subject,Marks as shown below:
sd
2.Then insert some data into the table.
sd1
3.In the first example how to display average marks scored by each student in each subject. We will display the StudentName and each SubjectName(IT,MATHS) as columns.


SELECT *
FROM StudentDetails PIVOT (avg(Marks) FOR subject IN ([IT], [Maths])) AS Aggregate

In the above code the result will be StudentName and Subject Names(IT,Maths) as column names and average of the marks scored in each subject by each student as shown below:
sd3
4.In the second example we will display the maximum marks scored by each student in each subject as shown below:
sd4

SELECT *
FROM StudentDetails
PIVOT (max(Marks) FOR subject IN ([IT], [Maths])) as max


5.In the third example we will display student names as column names and calculate the maximum marks scored by each student in each subject.
sd6


SELECT *
FROM StudentDetails
PIVOT (max(Marks) FOR studentname in ([priya],[seshu])) max



Note:
1.When using Pivot keyword in sqlserver, make sure you dont specify the column names explicity in the select clause otherwise it will give an error:done use sql statement as below:
SELECT subject,marks
FROM StudentDetails
PIVOT (max(Marks) FOR studentname in ([priya],[seshu])) max
instead use select * from...
2.Make sure you give an alias after the sql statement (max in the above queries) otherwise it will give an error as incorrect syntax near ')'.


Article by Vaishali Jain
Miss. Jain Microsoft Certified Technology Specialist in .Net(Windows and Web Based application development)

Follow Vaishali Jain or read 127 articles authored by Vaishali Jain

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: