Saturday, December 11, 2010

How to aggregate BIT Columns with Group By in SQL Server

This is a very common requirement in sql when you are deveploping applications.
You can achive this with very simple query, using cast and min sql functions.

Example:

create table user_reports
(id int identity, username varchar(20),report_name varchar(20), report_available bit)
go
insert into user_reports(username,report_name,report_available)
select 'Ajay', 'report1',1
union all
select 'Ajay', 'report2',1
union all
select 'Ajay', 'report3',1
union all
select 'Ajay', 'report4',1
union all
select 'John', 'report5',0
union all
select 'John', 'report6',1
union all
select 'John', 'report2',0
union all
select 'Tony', 'report1',1
union all
select 'Tony', 'report7',1
union all
select 'Ram', 'report3',1
union all
select 'Ram', 'report4',0
union all
select 'Ram', 'report8',1


-- This simple sql query will return user wise aggregated report_available column value
select username as UserName, cast(min(cast(report_available as int)) as bit) as 'Is Report Available'
from user_reports group by username

1 comment:

Tanu Tripathi said...

Thanks for sharing your fabulous idea. This blog is really very useful.SQL Jobs