2015-08-13 27 views
0

我有一個表像註冊這 -如何UNPIVOT動態

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

而且我要像這 -

Class1 has 3 Students 

Class2 has 2 Students 

Class3 has 3 Students 

我輸出我已經做了查詢,像這個 -

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; 

但是,如果有更多的班級比我每次在我的子句中都有變化。我也不知道pl/sql。所以如果有人可以幫忙?

+0

不要使用'count()'作爲集合函數,而是使用'sum()'作爲集合函數。 'select classname ||'有'|| sum(num)||'學生'作爲no_of_students從組類' – ridi

+0

不需要那個計數也將給出所需的結果,因爲它會計算rowid whre num = 1。除此之外,我想要怎麼做動作? –

+0

你可以提供一個數據 - 表'的結構enrol' – ridi

回答

1
-- it is an old-school solution, but it worked for me 
-- step 1 
create or replace procedure test_students 
as 

cursor c_cols 
is 
select column_name 
from user_tab_columns 
where table_name = 'ENROLL' 
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 enroll '; 

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; 




end; 

-- step 2 
begin 
test_students; 
end; 
/
+0

你真棒。謝謝夫人!!! –

+0

我不知道這是什麼類型的問題,但當我試圖執行test_students比它顯示'匿名塊已完成' 早些時候它正在運行,但現在發生了什麼? –

+0

當您執行第2步語句時,您將不得不「啓用dbms_output」。在SQL +中,命令類似'> set serveroutput on size 1000000'。在蟾蜍,你將不得不將紅色按鈕切換到綠色(這將enabale輸出int蟾蜍)。 – ridi