oracle sql 语句通过数据透视、分组依据或窗口获取计数?甲骨文11克
oracle sql statement to get counts with pivot, group by or windowing? oracle 11g
是否有可能并且有人可以给我一个很好的例子,在一个查询中选择一个结果集,returns 对人口统计或按特定分组的其他事物进行计数?这听起来很神秘,所以我将添加一个示例输出来说明我要传达的内容。我想要这样的结果集:
因此,对于每个 class,为性别填充的字段计数、男性计数、女性计数、填充的种族数量等等。
所以像
Select curricul.class,计数(stu.gender),计数(stu.race),计数(stu.eth)
从课程,斯图
按 class 分组
pivot( count(gender) for gender in (male, female)
您可以简单地使用:
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 ;
是否有可能并且有人可以给我一个很好的例子,在一个查询中选择一个结果集,returns 对人口统计或按特定分组的其他事物进行计数?这听起来很神秘,所以我将添加一个示例输出来说明我要传达的内容。我想要这样的结果集:
因此,对于每个 class,为性别填充的字段计数、男性计数、女性计数、填充的种族数量等等。
所以像 Select curricul.class,计数(stu.gender),计数(stu.race),计数(stu.eth) 从课程,斯图 按 class 分组 pivot( count(gender) for gender in (male, female)
您可以简单地使用:
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 ;