SQL GROUPING Function

The SQL GROUPING is one of the Aggregate Functions, which is used to indicate whether the specified column in a GROUP BY Clause aggregated or not. This Grouping function will return one for aggregated and zero for not aggregated.

SQL Grouping Function Syntax

The basic syntax behind this aggregate Grouping in SQL Server is as shown below:

SELECT GROUPING ([Column_Name])
FROM [Source]
GROUP BY [Column_Name]

For this grouping function example, we are going to use the [MyEmployee table] and it has 14 records.

SQL Grouping Function 2

SQL Grouping Function Example

The Grouping in SQL Server returns whether the grouping on the defined column has happened or not, by returning 0 and 1. In this grouping function example, we will show you the same.

SELECT [Education]
      ,[Occupation]
      ,GROUPING([Occupation]) AS 'Grouping'
      ,GROUPING([Education]) AS 'Grouping 2'
      ,SUM([YearlyIncome]) as income
FROM [MyEmployees Table]
GROUP BY [Education]
        ,[Occupation] WITH ROLLUP
SQL Grouping Function 1

The following Aggregate Function statements check whether the Grouping performed on the Education, and Occupation columns ar not by returning 1 and 0

 ,GROUPING([Occupation]) AS 'Grouping'
 ,GROUPING([Education]) AS 'Grouping 2'

TIP: Please refer to the GROUP BY Clause to understand the SQL Server Grouping techniques.

Categories SQL