SQL练习题目(MySQL)

Posted zhengyyao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL练习题目(MySQL)相关的知识,希望对你有一定的参考价值。

有如下员工表employee:

建表sql为:

CREATE TABLE `employee` (
`id` int(11) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`salary` int(11) DEFAULT NULL,
`deptid` int(11) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)

1.查出每个部门高于部门平均工资的员工名单

select a.deptid,a.name from employee a,(select deptid,avg(salary) as salary from employee group by deptid) b where a.deptid=b.deptid and a.salary>b.salary;

2、列出各个部门中工资高于本部门平均工资的员工数量和部门编号,并按部门编号排序

select a.deptid,count(a.id) as num from employee a,(select deptid,avg(salary) as salary from employee group by deptid) b where a.deptid=b.deptid and a.salary>b.salary group by a.deptid order by a.deptid;

3.求每个部门工资小于130000的人员的平均薪水

select deptid,avg(salary) as average_salary from employee group by deptid having avg(salary)<130000;

 4、统计各个薪水阶段的员工数量和占比

select salary_type,count(id) as num,count(id)*100/(select count(id) from employee)  as percent from (select id,case when salary<120000 then \'<12w\' when salary>=120000 and salary<150000 then \'12w~15w\' else \'>15w\' end as salary_type from employee) a group by salary_type;

5.统计各个部门各个年龄段的平均薪水

方法一:

select deptid, sum(case when age < 20 then salary else 0 end) / sum(case when age <20 then 1 else 0 end) as \'20岁以下平均工资\',  sum(case when age >= 20 and age <30 then salary else 0 end) / sum(case when age >= 20 and age <30 then 1 else 0 end) as \'20至30岁平均工资\',  sum(case when age >= 30 then salary else 0 end) / sum(case when age >=30 then 1 else 0 end) as \'>30岁及以上平均工资\'  from employee group by deptid;

方法二:

select deptid, age_type,avg(salary) as salary from (select id,salary,deptid,case when age <=20 then \'20岁以下平均工资\' when age>20 and age<=30 then \'20至30岁平均工资\' else \'大于30岁平均工资\' end as age_type from employee) a group by deptid,age_type;

 

以上是关于SQL练习题目(MySQL)的主要内容,如果未能解决你的问题,请参考以下文章

数据库LeetCode每日练习

练习题目及答案)

练习题目及答案)

SQL练习题题目

「MySql高级查询与编程」练习:企业员工管理

「MySql高级查询与编程」练习:企业员工管理