Uderc programming article aggregator sites

Sql for CrossTab Query

Advertisement
I have the following data on a student table
Regno        Term1          MnMark      Status
xxxx            1                  30            Red
xxxx            2                   50         Amber
xxxx            3                 40           Amber
xxxx           4                 90            Green
I wanto get the report like
Regno              Red           Amber               Green
xxxx                1                    2                    1
Like that. Please give help with proper query
With Thanks
Pol
polachan
Advertisement
The best answer: create table students (Regno varchar(50), Term1 int, MnMark int, Status varchar(50))
Insert into students values('xxxx',1,30,'Red'),('xxxx',2,50,'Amber'),('xxxx',3,40,'Amber'),('xxxx',4,90,'Green')
declare @cols varchar(200)
declare @sql varchar(2000)
Select @Cols = COALESCE(@Cols + ', ', '') + QUOTENAME(Status) FROM (select distinct Status from students) t
Select @sql='Select Regno, ' + @Cols+' FROM (Select Regno, MnMark, Status from students) src pivot (Count(MnMark) For Status IN (' + @Cols + ' )) pvt'
--Print @sql;
exec (@sql)
--Select Regno,[Red],[Amber], [Green] FROM (Select Regno, MnMark, Status from students) src pivot (Count(MnMark) For Status in ([Red],[Green],[Amber])) pvt
drop table students