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;
您正在使用哪些DBMS? Postgres的?甲骨文? – 2014-10-28 14:04:33
Oracle。我不確定它是否重要,但我正在使用Oracle SQL Developer。 – b00kgrrl 2014-10-28 14:09:54
Option1不起作用,因爲您無法在同一個選擇列表中引用列別名。 Option2是可以的,除了「percent_id_NULL」之後的逗號 – Multisync 2014-10-28 14:21:47