Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Cross tab query

Author  Topic 

byomjan
Starting Member

34 Posts

Posted - 2010-08-27 : 18:46:22
create table dbo.student
(Rollno int primary key identity,
student_name varchar(30),
House varchar(10),
grade char(1) )

Create table dbo.grade
( grade char(1) ,
description varchar(20)
)

insert into dbo.student
select 'John','Red', 'B'
union all
select 'Shri','Red', 'C'
union all
select 'Chow','Green', 'A'
union all
select 'Ramesh','Green', 'A'
union all
select 'Ken', 'Yellow','D'
union all
select 'Anil','Yellow', 'A'

Insert into dbo.grade
select 'A','Above 90'
union
select 'B','Between 80 and 90'
union
select 'C','Between 70 and 80'
union
select 'D','below 70'

Select
case House when 'Red' Then 'Red'
When 'Green' Then 'Green'
When 'Yellow' Then 'Yellow' end as House ,
count (case when grade='A' then 1 end ) as 'Above 90',
count (case when grade='B' then 1 end ) as 'Between 80 and 90',
count (case when grade='C' then 1 end ) as 'Between 70 and 80',
count (case when grade='D' then 1 end ) as 'below 70'

From student
group by house

I am getting the desired result . But can i use any smarter function than case statements to count the grades ?

Byomjan....

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-08-28 : 01:11:13
you can use PIVOT also to achieve. Look in books online for details.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-08-31 : 07:42:49
Refer this
http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -