Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server / SQL-Server-2008

Grouping dynamically on different columns in single query

0.00/5 (No votes)
4 Jan 2013CPOL 11.7K  
Grouping dynamically on different columns in single query

Introduction

Dynamic grouping is a big problem when you want to show grouping on different columns in the same query so either you need to write different queries or do some kind of dynamic query; instead of that, the solution I describe below will help to dynamically manipulate results.

Using the code

Grouping on different columns of a table incrementally by its hierarchy but conditionally, i.e.,

Grouping on organization hierarchy
Enterprise, Group, Company, RO, Branch

OR

Grouping on Employee hierarchy by Role
MD, CxO, GH, DH, Worker

OR

Grouping based on Time hierarchy
Hour, Minute, Sec, milisec

The SQL:

SQL
declare @Groupby int
set @Groupby = 2 

-- 1 shall do group by miliSec

-- 2 shall do group by Secs

-- 3 shall do group by Minute



Select 

case when @Groupby <= 4 then Hour else 'All' end as Hour,

case when @Groupby <= 3 then Minute else 'All' end as Minute,

case when @Groupby <= 2 then Secs else 'All' end as Secs,

case when @Groupby <= 1 then milisec else 'All' end as milisec

Sum(Cases) as NoOfCases

From TimeDim

GroupBy Hour, Minute, Secs, milisec 

Points of Interest

Use this in code at places where on user selection we wanted to show summary reports.

History 

First version released.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)