2014-10-28 104 views
0

我想知道多少百分比的記錄具有給定值,其中百分比定義爲與值匹配的記錄數除以記錄總數。即如果有100條記錄,其中10條對於student_id具有空值而20條具有999999的值,那麼percentage_999999應該是20%。我可以使用AVG功能來確定嗎?使用AVG函數確定SQL查詢中的百分比

選項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; 
+0

您正在使用哪些DBMS? Postgres的?甲骨文? – 2014-10-28 14:04:33

+0

Oracle。我不確定它是否重要,但我正在使用Oracle SQL Developer。 – b00kgrrl 2014-10-28 14:09:54

+0

Option1不起作用,因爲您無法在同一個選擇列表中引用列別名。 Option2是可以的,除了「percent_id_NULL」之後的逗號 – Multisync 2014-10-28 14:21:47

回答

0

我創建與100條記錄,20 999999999s,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子句選擇特定的年/大學(和擺脫一行一行),看看你是否能得到你期望的結果。