按sql

时间:2016-11-10 18:18:16

标签: sql postgresql sorting aggregate

假设我有以下学生数据:

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

然后我用一些脚本语言重新组织结果。但这太慢了。我希望通过一个查询获得正确的结果

1 个答案:

答案 0 :(得分: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