ROLLUP in Sql Server

it is used to Summarizing Data..

The ROLLUP operator is useful in generating reports that contain subtotals and totals. The ROLLUP operator generates a result set that is similar to the result sets generated by the CUBE operator.

ROLLUP generates a result set that shows aggregates for a hierarchy of values in the selected columns.

Checkout this example..

Create Table Student
(
StudentID int,
Student_Name Varchar(15),
SubjectName Varchar(15),
Marks_Scored numeric(18,1)
)

Insert into Student Values(1,'Babu', 'Tamil',90)
Insert into Student Values(1,'Babu', 'English',78)
Insert into Student Values(1,'Babu', 'Maths',88)
Insert into Student Values(1,'Babu', 'Science',88)
Insert into Student Values(1,'Babu', 'Social Science',92)

Insert into Student Values(2,'Ramesh', 'Tamil',92)
Insert into Student Values(2,'Ramesh', 'English',88)
Insert into Student Values(2,'Ramesh', 'Maths',98)
Insert into Student Values(2,'Ramesh', 'Science',99)
Insert into Student Values(2,'Ramesh', 'Social Science',90)

Insert into Student Values(3,'ram', 'Tamil',65)
Insert into Student Values(3,'Ram', 'English',68)
Insert into Student Values(3,'Ram', 'Maths',88)
Insert into Student Values(3,'Ram', 'Science',59)
Insert into Student Values(3,'Ram', 'Social Science',60)

select Student_Name,Sum(Marks_Scored) as Total
from Student
group by Student_Name
with rollup

Select
(Case When (Grouping(Student_Name)=1) Then 'G.Total' Else Student_Name End)as Student_Name,
(Case When (Grouping(SubjectName)=1) Then 'Total' Else SubjectName End)as SubjectName,
Sum(Marks_Scored) as Total
from Student group by Student_Name, SubjectName with rollup






Note :it will run sqlserver2005 and above

No comments: