sql语句中group by使用

group by分组函数,group by name
将查询结果按照name进行分组,相同name的记录一组,配合聚合函数,显示每个name的情况。
 

1,数据源

表A结构如下:

CREATE TABLE C
(
ID INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
classid INT,
sex VARCHAR(10),
age INT
)

--添加测试数据
    Insert into C(classid,sex,age) values(1,'男',20)
    Insert into C(classid,sex,age) values(2,'女',22)
    Insert into C(classid,sex,age) values(3,'男',23)
    Insert into C(classid,sex,age) values(4,'男',22)
    Insert into C(classid,sex,age) values(1,'男',24)
    Insert into C(classid,sex,age) values(2,'女',19)
    Insert into C(classid,sex,age) values(4,'男',26)
    Insert into C(classid,sex,age) values(1,'男',24)
    Insert into C(classid,sex,age) values(1,'男',20)
    Insert into C(classid,sex,age) values(2,'女',22)
    Insert into C(classid,sex,age) values(3,'男',23)
    Insert into C(classid,sex,age) values(4,'男',22)
    Insert into C(classid,sex,age) values(1,'男',24)
    Insert into C(classid,sex,age) values(2,'女',19)

2,group by

sql语句中,select classid from  A group by classid,首先从表A中查询出所有记录,再将记录按照classid分类,每一类为一条记录。

能否显示其他字段呢?select classid,age from  A group by classid,这样不可以的,因为按照classid分类,每一类classid记录中classid是相同的,对应一条记录,但是age不一定相同,一次一条记录无法显示多个age。因此不可以显示age字段,此处会出错。但是我们可以显示相同classid字段所有记录的平均年龄,这样就是多条记录缩减为一条记录,这就是聚合函数。如:select classid,avg(age) from  A group by classid,这是可以的。

3,group by 多个条件

如果group by后面多个条件,比如字段a1和a2,则将查询的所有记录,根据a1和a2分为k类显示。即a1+a2是一个新的字段。

4,如果需要对每个分组中记录做条件筛选,需要使用having。

我们首先根据where条件,将数据集select出来。之后跟group by结果集分组,之后利用having去除每个分组中不符合条件的记录。

having后面经常跟聚合函数,聚合函数不能跟在where后面,只能跟在having后面。

原文地址:https://www.cnblogs.com/usa007lhy/p/3393551.html