2016-11-10 43 views
1

總值比方說,我有以下的學生數據:排序在SQL

classroom  gender student_id 
------------------------------------- 
First Grade M  123 
First Grade F  124 
First Grade F  125 
Second Grade M  126 
Third Grade M  127 
... 

我想產生以下結果:頂部由學生與細節每個總數下令3個最大的教室:

classroom   boys_count girls_count total_count 
-------------------------------------------------- 
Third Grade  30   30   60 
First Grade  20   5   25 
Fourth Grade  10   10   20 

我怎麼能在SQL中做到這一點?如有必要,我可以使用特定的postrges功能。


我試過至今:在一些腳本語言

SELECT count(*) as total_count 
    , gender 
    , classroom 
ORDER BY 1 
GROUP BY classroom, gender 
LIMIT 3 

然後我重新組織的結果。但是這太慢了。我想用一個查詢獲得正確的結果

+2

這是一個非常基本的SQL查詢。你知道這種語言嗎? –

+0

這不是聚合。這是簡單的補充和排序。 –

+0

@GordonLinoff True。我意識到我過分簡化了我的真正問題。我會編輯我的問題 –

回答

1
select classroom as name, 
     sum(case when gender = 'M' then 1 else 0 end) as boys_count, 
     sum(case when gender = 'F' then 1 else 0 end) as girls_count, 
     count(*) as total_count 
from your_table 
group by classroom 
order by count(*) desc 
limit 3 
+0

有三種替代方法:'count(*)過濾器(其中性別='M')與boys_count','count(nullif(gender,'F'))作爲boys_count'和'sum (gender ='M'):: int)作爲boys_count'取決於你更可讀的內容。 – Abelisto

+0

工作就像一個魅力。謝謝。 (不知道爲什麼,我試圖「按性別分組」,只需按教室分組即可) –