oracle sql语句通过pivot,group by或windowing获取计数? oracle 11g

时间:2016-05-20 14:11:26

标签: oracle plsql oracle-sqldeveloper plsqldeveloper mod-plsql

是否有可能并且有人可以给我一个很好的例子,在一个查询中选择一个结果集,该结果集返回特定分组的人口统计或其他事物组的计数?这听起来很神秘,所以我要添加一个我想要传达的示例输出。我想要一个结果集如:

enter image description here

因此,对于每个班级,填充性别的字段数,男性的数量,女性的数量,已填充的种族数量等等。

等等 选择curricul.class,count(stu.gender),count(stu.race),count(stu.eth)  来自curricul,stu 按班组 pivot(男性,女性)中性别的计数(性别)

1 个答案:

答案 0 :(得分: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 ;