Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Cube in SQL Server

Suggested Videos
Part 100 - Send datatable as parameter to stored procedure
Part 101 - Grouping sets in SQL Server
Part 102 - Rollup in SQL Server



Cube() in SQL Server produces the result set by generating all combinations of columns specified in GROUP BY CUBE(). 



Let us understand Cube() in SQL Server with examples. We will use the following Employees table for the examples in this video. 
Employees Table

Write a query to retrieve Sum of Salary grouped by all combinations of the following 2 columns as well as Grand Total.
Country,
Gender 

The output of the query should be as shown below
sql server group by with cube

Using Cube with Group By
SELECT Country, Gender, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY Cube(Country, Gender)

--OR

SELECT Country, Gender, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY Country, Gender with Cube

The above query is equivalent to the following Grouping Sets query
SELECT Country, Gender, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY
    GROUPING SETS
    (
         (Country, Gender),
         (Country),
         (Gender),
         ()
    )

The above query is equivalent to the following UNION ALL query. While the data in the result set is the same, the ordering is not. Use ORDER BY to control the ordering of rows in the result set.

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

5 comments:

  1. Thanks Venkat Sir,for wonderfull effort.I know you have discussed extensivley Web services Using SOAP.But most of the organization prefer to use REST web services Please make a single tutorial how we can make Web services using Rest.I search on web so many times but did not get any solid way of making REST Web services.

    ReplyDelete
  2. where is the like button?

    ReplyDelete
  3. Please add the create and insert script for a employee table

    ReplyDelete
    Replies
    1. https://csharp-video-tutorials.blogspot.com/2015/09/grouping-sets-in-sql-server.html

      Delete
  4. awesome content on SQL Kudvenkat sir. I refer your SQL series as a one stop shop for SQL!

    ReplyDelete

It would be great if you can help share these free resources