SQL练习题目(MySQL)

时间:2023-02-23 13:46:46

有如下员工表employee:

SQL练习题目(MySQL)

建表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;

SQL练习题目(MySQL)

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;

SQL练习题目(MySQL)

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

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

SQL练习题目(MySQL)

 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;

SQL练习题目(MySQL)

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;

SQL练习题目(MySQL)

方法二:

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)