group by 几种不同情况下的聚合运算

1、比较常见的一种情况,比如说:查询每个班级里学生的成绩的和

select c.className , sum(u.score) as '成绩' from classes c left join user u on c.id = u.classid group by c.id

2、查询每一个班级中男生和女生的人数

select 
  c.className , 
  sum(case when u.sex=1 then 1 else 0 end) as '男生人数',
  sum(case when u.sex=0 then 1 else 0 end) as '女生人数'
from
  classes c 
  left join user u on c.id = u.classid
group by c.id 

 

posted @ 2020-06-10 10:11  西风恶  阅读(705)  评论(0编辑  收藏  举报