Click here to Skip to main content
15,885,143 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
I have a table enroll like this-

Students                Class1               Class2                   Class3
student1                 1                      0                       1
student2                 0                      1                       0
student3                 1                      1                       0
studnet4                 0                      1                       1

And I want I output like this-

Class1 has 3 Students

Class2 has 2 Students

Class3 has 3 Students

I have made a query for that like this-

SQL
select classname||' has '||count(num)||' students 'as no_of_students from
(
select * from enroll )
unpivot (
num for classname in (class1,class2,class3)
) 
where num=1
group by classname;


But if there are more class than every time I had change in my in clause. I don't know pl/sql also.I have tried it using but I am failing. So if anyone can help?
Posted
Updated 14-Aug-15 2:40am
v5
Comments
Richard Deeming 14-Aug-15 9:44am    
That looks like a very bad database design.

You should have three tables: students, classes, and enrolment. The enrolment table would just contain the primary key of a student and the primary key of a class, indicating that the student was enrolled in that class.

1 solution

Solution is-

create or replace procedure test_students
as

cursor c_cols
is
select column_name
from user_tab_columns
where table_name = 'STUDENTSENROLL'
and column_name != 'STUDENTS';

l_number_of_students number;
l_my_col user_tab_columns.column_name%type;
l_statement varchar2(30000);

begin



for r_cols in c_cols loop

l_my_col := r_cols.column_name;

l_statement :=
' select sum('||l_my_col||')
from studentsenroll ';

execute immediate l_statement into l_number_of_students;

dbms_output.put_line ('Number of students: '||l_number_of_students ||'in Class :'||l_my_col);

end loop;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900