码迷,mamicode.com
首页 > 数据库 > 详细

SQL练习题目(MySQL)

时间:2017-08-06 17:07:57      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:int   统计   count   and   年龄   select   阶段   where   com   

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

标签:int   统计   count   and   年龄   select   阶段   where   com   

原文地址:http://www.cnblogs.com/zhengyyao/p/7295113.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!