当前位置: 代码网 > it编程>数据库>Mysql > mysql之DML的select分组排序方式

mysql之DML的select分组排序方式

2024年09月14日 Mysql 我要评论
一、创建表employee和department表1.创建department表create table department(-> depart_id int primary key auto

一、创建表employee和department表

1.创建department表

create table department(
-> depart_id int primary key auto_increment comment '部门编号',
-> depart_name varchar(50) not null comment '部门名称'
-> ) auto_increment=1001;

2.创建employee表

create table employee( n for the right syntax to use near 'redsodsnvjnv' at line 1
-> emp_num int primary key auto_increment comment '员工编号',
-> emp_name varchar(30) not null comment '员工姓名',
-> emp_job varchar(30) not null comment '员工岗位',
-> hire_data datetime not null comment '入职时间',
-> salary int not null comment '薪资',
-> bonus int not null comment '奖金',
-> dept_id int comment '部门编号'
-> );

3.给employee表格和department表格建立外键

alter table employee add constraint emp_dept_fk foreign key(dept_id) references department(depart_id);

4.给department插入数据

insert into department values(null,'科技部门'),(null,'法律部门'),(null,'后勤部门'),(null,'财务部门');

5.给employee表插入数据

insert into employee values((null,'张三','工程师','2023.9.1',12000,1000,1001),(null,'张四','工程师','2023.9.1',11000,1010,1001),(null,'李三','会计','2023.9.1',5000,300,1004),(null,'张六','保安','2023.9.1',5000,500,1003),(null,'刘律','律师','2023.9.1',1000,1,1002);

6.删除名字为那个的数据

delete from employee where emp_name='那个';

二、分组查询和排序查询,以及对数据的处理(avg,sum,count,max,min)

1.根据dept_id进行分组并查询他们的平均工资

select dept_id,avg(salary) from employee group by dept_id;

2.根据dept_id分组查询他们年薪平均值

select dept_id, avg((salary+bonus)*12) from employee group by dept_id;

3.根据dept_id分组查询他们薪资的最高值

select dept_id,max(salary) from employee group by dept_id;

4.根据dept_id分组查询他们薪资的最低值

select dept_id,min(salary) from employee group by dept_id;

5.根据dept_id分组查询他们薪资的总和

select dept_id,sum(salary) from employee group by dept_id;

6.根据dept_id分组查询人数的总和

select dept_id,count(*) from employee group by dept_id;

7.根据dept_id分组查询人数的总和

select dept_ip,count(emp_name) from employee group by dept_id;

8.按照dept_id降序的方式查询emp_name和dept_id

select emp_name,dept_id from employee order by dept_id;

9.按照dept_id和emp_job分组查询薪资总和

select dept_id,emp_job,sum(salary) from employee group by dept_id, emp_job;

10.在dept_id组中限制只查询工资总和大于10000的薪资,并展现出来工作和薪资

select dept_id,emp_job,sum(salary) from employee group by dept_id,emp_job having sum(salary>1000);

三、select查询之limit限制

1.查询前三行数据

select * from employee limit 0,3;

2.查询第三条到第七条数据

select * from employee limit 2,7;

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com