Conditional group by in SQL Server

In this post, we are going to learn how we can apply a conditional GROUP BY clause on a column, based on the values of another column. Assume that we have a table named tbl_EmpSaleDetail which contains the sales records for each employee. Let’s have a look at the table data.

Sample data

Sample data

In the above table, we have these columns:

EmpName – Stores the name of the employee

SaleDate – Date of sale

SaleAmount – Amount of the sale

IsActive – Indicates whether the employee is active or not.

Now, we need this output.

Required output

Required output

In this output, we can see that all the data of inactive employees have been aggregated to a single row labeled as “–Inactive Employees Sales–” (Highlighted in red). However, the sum of the sales of the active employees are aggregated individually. Before writing the conditional group by query, lets create the sample table with dummy data using this script.

IF OBJECT_ID('dbo.tbl_EmpSaleDetail') IS NOT NULL
	DROP TABLE dbo.tbl_EmpSaleDetail
--Create a sample table now
CREATE TABLE dbo.tbl_EmpSaleDetail
	EmpName VARCHAR(256),
	SaleAmount DECIMAL(18,2),
	IsActive BIT

Conditional GROUP BY query – SQL Server

There could be several ways to achieve the above output using T-SQL queries. However, in this post, we will be using a conditional group by clause in order to get the required output. This is the script to generate the required output data.

CASE WHEN IsActive = 1 THEN EmpName ELSE '--Inactive Employees Sales--' END AS EmpName, 
SUM(SaleAmount) AS TotalSale 
FROM dbo.tbl_EmpSaleDetail
GROUP BY CASE WHEN IsActive = 1 THEN EmpName ELSE '--Inactive Employees Sales--' END

In the above query, we have used a CASE expression in GROUP BY clause to dynamically convert the inactive employee names to a fixed string value “–Inactive Employees Sales–“. We have used the same CASE expression in the SELECT statement also. Otherwise it will throw an error message “Column ‘dbo.tbl_EmpSaleDetail.EmpName’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

If we want to show this value at top or at the bottom, we can use a similar trick as mentioned here.

Thanks for the reading. Please share your input in comments.

Rate This
[Total: 1   Average: 3/5]

Gopal Krishna Ranjan

About Gopal Krishna Ranjan

Gopal is a passionate Data Engineer and Data Analyst. He has implemented many end to end solutions using Big Data, Machine Learning, OLAP, OLTP, and cloud technologies. He loves to share his experience at Connect with Gopal on LinkedIn at

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.