Thursday, October 29, 2015

Cube Function in the SQL Server

Select State,City, Count(Acct_NUM) as TotalAccounts
From CustomerProfile
Group By Cube (State,City)

Select Country,Gender, Sum(Salary) as TotalSalary
From Employees
Group By Cube (Country,Gender)

Select Country,Gender, Sum(Salary) as TotalSalary
From Employees
Group By  Country,Gender With Cube


-------Group By, Country and Gender  then By Country then Gender and then all---------


Select Country,Gender, Sum(Salary) as TotalSalary
From Employees
Group By 
        Grouping SETS
         (
             (Country,Gender),
             (Country),
             (Gender),
             ()
        )

-- Now the Alternative of the above Query

Select Country,Gender, Sum(Salary) as TotalSalary
From Employees
Group By Country,Gender

UNION ALL

Select Country,NULL, Sum(Salary) as TotalSalary
From Employees
Group By Country

UNION ALL

Select NULL,Gender, Sum(Salary) as TotalSalary
From Employees
Group By Gender

UNION ALL

Select NULL,NULL, Sum(Salary) as TotalSalary
From Employees