How To Use Grouping Function in SQL

Introduction

Here, we will discuss about how to use Grouping function in SQL

One of the aggregate functions, SQL GROUPING, is used to determine whether or not the supplied column in a GROUP BY Clause is aggregated. If the data was aggregated, this grouping method will return one; otherwise, it will return zero.

SQL Grouping Function Syntax

This aggregate Grouping in SQL Server’s fundamental syntax is as follows:

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

We’ll utilize the [Employee table], which has 14 records, for this grouping function example.

Example of a SQL Grouping Function

SQL Server’s grouping function returns 0 or 1 depending on whether the defined column has been grouped or not. This example of a grouping function will demonstrate 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

The following aggregate function statements return 1 and 0 to determine whether grouping was performed on the education and occupation columns.

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

Thank you

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories