2016-05-20 25 views
-1

是否有可能並且有人能給我一個很好的例子,在一個查詢中選擇一個結果集,該結果集通過特定的分組返回人口統計或其他事物的計數?這聽起來很神祕,所以我要添加一個我想要溝通的示例輸出。我想要一個結果集,如:oracle sql語句可以通過pivot,group by或windowing來計算嗎? oracle 11g

enter image description here

因此,對於每一類字段的計數會填充性別,男性的計數,女的計數,計數是如何比賽的許多是人口等等。

因此,像 選擇curricul.class,計數(stu.gender),計數(stu.race),計數(stu.eth) 從curricul,STU 組按類 樞軸(計數(性別)對在性別(男,女)

+0

你還沒有告訴我們你從工作中的數據,表結構,或者是與查詢你」發生什麼(這是舊式的語法;與ANSI加入它會更明顯你缺少連接條件)。爲什麼h您是否包含圖片而不是文字,顯示您想要的內容?它看起來並不像你想旋轉一樣。你是否正在尋找'count(case ... end)'來獲得男性/女性的數字? –

回答

3

你可以簡單地使用:

with curricul as 
(select 1 classid, 'Math' class from dual union all 
select 2, 'Literature' from dual 
) 
, 
student as 
(select 1 id, 1 classid, 'male' gender, 1 race, 1 eth from dual union all 
    select 2, 1, 'female', 1, 2 from dual union all 
    select 3, 1, 'male' , 3, 1 from dual union all 
    select 4, 1, 'male' , 5, 7 from dual union all 
    select 5, 1, 'female', 4, 8 from dual union all 
    select 6, 1, 'male' , 1, 6 from dual union all 
    select 7, 2, 'female', 3, 4 from dual union all 
    select 8, 2, 'female', 1, 1 from dual union all 
    select 9, 2, 'female', 7, 9 from dual union all 
    select 10, 2, 'male' , 9, 1 from dual union all 
    select 11, 2, 'female', 8, 1 from dual 
) 
select s.classid, curricul.class 
    ,count(s.gender) as count_gender 
    ,sum(case when gender = 'male' then 1 else 0 end) as count_male 
    ,sum(case when gender = 'female' then 1 else 0 end) as count_female 
    ,count(s.race) as count_race 
    ,count(s.eth) as count_ethnicity 
from student s 
inner join curricul 
    on s.classid = curricul.classid 
group by s.classid, curricul.class ; 
+2

如果性別爲空,那麼'count(性別)'和'count(*)'可以給出不同的結果。同樣,你可能不希望你的計數中有不同 - 它可能只是計算有多少人被填充,特別是。給出例子中的數字。事實上,它說在這個問題中,倒數第二段。 –

+0

@AlexPoole啊,謝謝你的可空和解釋 –