分组
group by 根据谁分组,可以求这个组的最大值,最小值,平均值,求和,但是这个求出来的值只是和分组字段对应
并不和其他任何字段对应,这个时候查出来的所有其它字段都不生效
select post,group_concat(emp_name) from employee group by post;
select podt,group_concat(emp_name) from employee group by post;
聚合函数
count 求个数
select sex,count(id) from employee group by sex;
max 求最大值
select post,max(salary) from employee group by post;
min 求最小值
select post,min(salary) from employee group by post;
sum 求和
avg 求平均
select sex,avg(salary) from employee group by sex;
select sex,count(age) from employee group by sex;
having 过滤语句
在having条件中可以使用聚合函数,where中不行。
select post,avg(salary) from employee group by post having avg(salary)>10000; 平均薪资大于10000的部门
适合去筛选符合条件的莫一组数据,而不是某一行数据。
先分组在过滤:求平均薪资大于xx的部门,求人数大于xx的性别,求大于xx人的年龄段。
select age,count(id) from employee group by age having count(id)>5;
select sex,count(id) from employee group by sex having count(id)>5;
select post,group_concat(emp_name),count(id) from employee group by post having count(id)<2;
根据薪资多少进行排序 order by 默认是升序(asc) desc降序
select * from employee order by salary; 从小到大
select * from employee order by salary desc; 从大到小
select * from employee order by age,salary; 根据年龄从小到大排。
select * from employee order by age,salary; 当年龄相同时,依照薪资从小到大排。
取出薪资排名最高的人 limit 1
select emp_name,salary from employee order by salary desc limit 1;
limit m,n limit m,offset n 两个一样
从m+1项开始,取n项
如果不写m,m默认为0
select emp_name,salary from employee order by salary desc limit 1,3; 取第2,3,4名的薪资
原文:https://www.cnblogs.com/ch2020/p/12902197.html