Thursday, August 30, 2012

ROLLUP in SqlServer

ROLLUP clause is used to do aggregate operation on multiple levels in hierarchy. 



CREATE TABLE [dbo].[Emp](
      [EmpID] [varchar](5) NULL,
      [EmployeeName] [varchar](50) NULL,
      [Amount] [decimal](18, 2) NULL
) ON [PRIMARY]

GO



INSERT emp(EmpID,EmployeeName,Amount)       VALUES('100','Shan.R','50000.00')
INSERT emp(EmpID,EmployeeName,Amount)       VALUES('101','Ramya','20000.00')
INSERT emp(EmpID,EmployeeName,Amount)       VALUES('102','Raju','90000.00')
INSERT emp(EmpID,EmployeeName,Amount)       VALUES('103','Karthi','5000.00')
INSERT emp(EmpID,EmployeeName,Amount)       VALUES('104','Suresh','6000.00')


Go



SELECT
CASE WHEN EmpID IS NULL THEN 'Total' ELSE EmpID END AS EmpID ,sum(Amount) AS  Amount FROM Emp
GROUP BY EmpID
WITH ROLLUP

Go
Result:


No comments: