T-SQL Tutorial

CUBE clause


SQL Server CUBE clause is a powerful feature of Microsoft SQL Server that allows users to generate cross-tabulated or multidimensional results based on a set of specified columns. It is a method for performing multi-dimensional analysis of data, and it is useful for summarizing and aggregating data across multiple dimensions.

The CUBE clause in SQL Server allows users to generate all possible combinations of subtotals and grand totals for a specified set of columns in a table or a query result. This means that with the CUBE clause, users can easily create reports that provide a comprehensive view of data across multiple dimensions.


Syntax

The syntax for the CUBE clause is as follows:

SELECT column1, column2, ..., columnN, aggregate_function(columnX)
FROM table_name
GROUP BY CUBE(column1, column2, ..., columnN);


Example

To use the CUBE clause, users must include the keyword CUBE in the SELECT statement followed by a list of column names. For example, the following query uses the CUBE clause to generate subtotals and grand totals for the columns "Region," "Product," and "Year":

SELECT Region, Product, Year, SUM(Sales) AS TotalSales
FROM Sales
GROUP BY CUBE(Region, Product, Year)

The above query will generate all possible combinations of subtotals and grand totals for the Region, Product, and Year columns. The resulting output will include subtotals for each region and product, subtotals for each region and year, subtotals for each product and year, and a grand total for all regions, products, and years.

In addition to the CUBE clause, SQL Server also provides the ROLLUP and GROUPING SETS clauses, which can be used to perform similar multidimensional analysis of data.

Overall, the SQL Server CUBE feature is a powerful tool that enables users to generate comprehensive reports and perform multidimensional analysis of data with ease.