数据库分组(group by详解)--【SQL Server】

分组:group by 列名1,列名2…
聚合函数一般结合分组使用,进行分组内的数据进行统计
根据指定列进行分组

select COUNT(*)
from studentinfo
group by sgender--计算男女分别总数是多少
select studentinfo.sgender ,studentinfo.cid ,classinfo.cname,COUNT(*) 
from studentinfo
inner join classinfo on classinfo.cid=studentinfo.cid
group by studentinfo.sgender,studentinfo.cid,classinfo.cname
--求每班男女人数且显示班级(先分男女,再分班级)

注:select后面只能跟group by后面跟过的

--统计学生编号大于2各班级的各性别的学生人数
select sgender,cid,COUNT(*)
from studentinfo
where sid>2
group by sgender,cid

分组后条件筛选:having …

--统计学生编号大于2各班级的各性别的学生人数大于1的信息
select sgender,cid,COUNT(*)
from studentinfo
where sid>2
group by sgender,cid having count(*)>1
发布了44 篇原创文章 · 获赞 4 · 访问量 1046

猜你喜欢

转载自blog.csdn.net/qq_44162236/article/details/104747758