MySQL分组操作

MySQL分组操作

返回首页

分组(group by)语法:

create table department (id int auto_increment primary key,

            title varchar(32),

             )engine = innodb default charset=utf8;

insert into department(title) values("运营"),("财务"),("公关")

  

create table userinfo (id int auto_increment primary key,

           name varchar(32),

           part_id int,

           constraint fk_user_part foreign key (part_id) references department (id)

          ) engine = innodb default charset=utf8;

insert into userinfo (name,part_id) values("wang",2),("george",3),("fat",1),("cool",3)

如何将用户George和cool放在一个组,因为George和cool都是部门3中的。

用group by方法,group by的意思是根据哪一列数据分组,根据的参数,放在group by 后面。

语法:select * from userinfo group by part_id;

样例:

select count(id),max(id),part_id from userinfo group by part_id;   # 显示都有哪些组,每组都有多少人。

max(id)的意思是在分组后,谁的id大,就取谁显示。

count(id)的意思是统计分组后,改组的人数,并显示。用于统计部门人数。

count 计数,意思是统计数量,
max 取值大的,谁大取谁。
min  取值小的,谁小取谁。
sum 求和。
avg  求平均值。

如果对于聚合函数结果进行二次筛选时?必须使用having ****

select count(id),part_id from userinfo group by part_id having count(id) > 1;

# 统计userinfo的表的pait_id相同组的成员个数,并进行二次筛选,成员数量大于1的。

select count(id),part_id from userinfo where id > 0 group by part_id having count(id) > 1;

# 用where进行二次筛选,不用有聚合函数,也就是这种方法不推荐。

------- END -------

原文地址:https://www.cnblogs.com/george92/p/7309779.html