LikeLike

]]>LikeLike

]]>from StudentsEnroll

union all

select ‘student2 has’+ CONVERT(varchar(10), SUM(class2) ) +’staudent’

from StudentsEnroll

union all

select ‘student3 has’+ CONVERT(varchar(10), SUM(class3)) +’staudent’

from StudentsEnroll

LikeLike

]]>sql

this site very helpful for me

keep it up……

LikeLike

]]>set @total =0

select ‘CLASS 1 HAS ‘ + case when class1=1 then CAST (SUM(@total+1)AS VARCHAR(10)) + ‘ STUDENTS’ end from StudentsEnroll

WHERE Class1 =1

group by Class1

UNION ALL

select ‘CLASS 2 HAS ‘ + case when class2=1 then CAST (SUM(@total+1)AS VARCHAR(10)) + ‘ STUDENTS’ end from StudentsEnroll

WHERE Class2 =1

group by Class2

UNION ALL

select ‘CLASS 3 HAS ‘ + case when class3=1 then CAST (SUM(@total+1)AS VARCHAR(10)) + ‘ STUDENTS’ end from StudentsEnroll

WHERE Class3 =1

group by Class3

LikeLike

]]>You asked to write a query about student enrollment where there are three classes ; Class1 , Class2 and Class3 and 4 students as Student1, Student2, Student3 and Student4. And there is a table StudentEnroll which has the data which depicts which student is enrolled to which class.

The format of the output should be The Class 1 has 3 students and so on; for all the classes.

You have provided the followin solution

DECLARE @Col INT

SET @Col = 1

WHILE (@Col < 4)

BEGIN

EXEC('SELECT ''Class'+@Col+' Has '' + CAST(COUNT(Students) AS VARCHAR(100)) + '' Students'' Results

FROM studentsenroll

WHERE Class'+@Col+' = 1

GROUP BY Class'+@Col)

SET @Col = @Col + 1

CONTINUE

END

Now, I can understand that you are considering only those students who have been enrolled and that's the reason the class'+@col+' = 1 is a constant value.

This can be easily done by using the Sum function. But, you have mentioned that if the scenario is dynamic then we have to use the Group By function. Could you please explain me the Dynamic scenario.

I'm sorry if I sound stupid.

Regards,

Lopa

LikeLike

]]>In expression class + ‘@col’ what is class and what is value in @col? Please provide details about your query.

Regards,

Pinal Dave

LikeLike

]]>You are doing a great job.

I may sound low, but could you please explain me the where clause of the above query. Why the class+’@col’ value is always constant?

Thanks,

Lopa

LikeLike

]]>select classname + ‘ has ‘ + Cast(total As Nvarchar(2)) + ‘ students’ from

(

select

sum(class1) class1,

sum(class2) class2,

sum(class3) class3

from studentsenroll

) p

unpivot

( Total for classname in (class1,class2,class3)) as S

LikeLike

]]>insert into xs values(‘stu1’,1,0,1)

insert into xs values(‘stu2’,1,0,1)

insert into xs values(‘stu3’,0,1,0)

insert into xs values(‘stu4’,1,0,1)

select sname+’has ‘+ cast((class1+class2+class3) as nvarchar(10))+’students’ from xs

LikeLike

]]>