使用AVG函数确定SQL查询中的百分比

时间:2014-10-28 14:03:06

标签: sql oracle

我想知道有多少记录具有给定值,其中百分比定义为匹配该值的记录数除以记录总数。即如果有100条记录,其中10条记录为student_id为空,20条记录的值为999999,则percentage_999999应为20%。我可以使用AVG功能来确定吗?

选项1:

SELECT year, college_name, 
       sum(case when student_id IN ('999999999') then 1 else 0 end) as count_id_999999999,
       count_id_999999999/total_id as percent_id_999999999,
       sum(case when student_id IS NULL then 1 else 0 end) as count_id_NULL,
       count_id_NULL/total_id  as percent_id_NULL
       count(*) as total_id
FROM  enrolment_data ed
GROUP BY year, college_name
ORDER BY year, college_name;

选项2:

SELECT year, college_name, 
       sum(case when student_id IN ('999999999') then 1 else 0 end) as count_id_999999999,
       avg(case when student_id IN ('999999999') then 1.0 else 0 end) as percent_id_999999999,
       sum(case when student_id IS NULL then 1 else 0 end) as count_id_NULL,
       avg(case when student_id IS NULL then 1.0 else 0 end) as percent_id_NULL
       count(*) as total_id
FROM  enrolment_data ed
GROUP BY year, college_name
ORDER BY year, college_name;

1 个答案:

答案 0 :(得分:0)

我创建了一个类似的表,包含100条记录,20个999999999,10个空值和70个1。这在SQL Server上对我有用:

select count(*), StudentID 
from ScratchTbl 
group by StudentID;

(No column name)    StudentID
10                  NULL
70                  1
20                  999999999

select avg(case when StudentID = '999999999' then 1.0 else 0.0 end) as 'pct_9s', 
       sum(case when StudentID = '999999999' then 1 else 0 end) as 'count_9s',
       avg(case when StudentID is null then 1.0 else 0.0 end) as 'pct_null', 
       sum(case when StudentID is null then 1 else 0 end) as 'count_null'
from ScratchTbl

pct_9s      count_9s    pct_null    count_null
0.200000    20          0.100000    10

我有一种感觉,你对group by子句的使用可能会给你带来麻烦,或许可以使用where子句选择一个特定的年份/学院(并逐行删除),看看你是否得到了结果你期待。