SQL练习题目(MySQL)

本文通过具体的SQL实战案例,展示了如何查询员工表中不同条件下的数据,包括高于部门平均工资的员工名单、部门平均薪资统计等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有如下员工表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;

 

转载于:https://www.cnblogs.com/zhengyyao/p/7295113.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值