65.9K
CodeProject is changing. Read more.
Home

Grouping dynamically on different columns in single query

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jan 4, 2013

CPOL
viewsIcon

11690

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:

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.