MySQL练习

一、有一张员工表emp,字段:姓名name,性别sex,部门depart,工资salary。查询以下数据:
1、查询男女员工的平均工资
2、查询各部门的总薪水
3、查询总薪水排名第二的部门
4、查询姓名重复的员工信息
5、查询各部门薪水大于10000的男性员工的平均薪水

1.select sex,avg(salary) from emp group by sex;
2.select depart,sum(salary) from emp group by depart;
3.select depart,sum(salary) from emp group by depart order by sum(salary) limit 1,1;
4.select name from emp group by name having count(*) > 1;
5.select depart,avg(salary) from emp where sex = '男' and salary > 10000 group by depart;

二、有员工表、部门表和薪资表,根据查询条件写出对应的sql

现在有员工表、部门表和薪资表。
部门表depart的字段有depart_id, name;
员工表 staff 的字段有 staff_id, name, age, depart_id;
薪资表salary 的字段有 salary_id,staff_id,salary,month。

(问题a):求每个部门’2016-09’月份的部门薪水总额

select
    dep.name,
    sum(sal.salary)
from 
    salary sal
    join staff sta on dep.depart_id = sta.depart_id
    join salary sal on sta.staff_id = sal.staff_id  
where year(sal.month) = 2016 and
   month(sal.month) = 9
group by dep.depart_id 

(问题b):求每个部门的部门人数,要求输出部门名称和人数

select
    dep.name,
    count(sta.taff_id)
from
    staff sta
    join depart dep on dep.depart_id = sta.depart_id
group by
    sta.depart_id

(问题c):求公司每个部门的月支出薪资数,要求输出月份和本月薪资总数

select
    dep.name,
    sal.month,
    sum(sal.salary)
from 
    depart dep 
    join staff sta on dep.depart_id = sta.depart_id
    join salary sal on sta.staff_id = sal.staff_id 
group by 
    dep.depart_id,
    sal.month   

三、写出以下数据库的查询条件
有两个表分别如下:
表A(varchar(32) name, int grade)
数据:zhangshan 80, lisi 60, wangwu 84

表B(varchar(32) name, int age)
数据:zhangshan 26, lisi 24, wangwu 26, wutian 26

写SQL语句得到如下查询结果:

NAME GRADE AGE
zhangshan 80 26
lisi 60 24
wangwu 84 26
wutian null 26
select B.name,grade,age from A right join B on A.NAME = B.NAME;

三、编写一个SQL查询,获取Employee表中第二高的薪水(Salary)
±----±------+
| Id | Salary|
±----±------+
| 1 | 100 |
±----±------+
| 2 | 200 |
±----±------+
| 3 | 300 |
±----±------+

例如上述Employee表,SQL查询应该返回200作为第二高的薪水。如果不存在第二高的薪水,那么查询应该返回null。
±--------------------+
| SecondHighestSalary |
±--------------------+
| 200 |
±--------------------+

#Write your MySQL query statement below
select (select distinct Salary from Employee order by  Salary  DESC limit 1,1) as SecondHighestSalary ;

四、已知T1和T2的字段定义完全相同,T1有5条不同数据,T2有5条不同数据,其中T1有2条数据存在表T2中,使用UNION语句查询这些数据,要求重复数据不出现

SELECT * FROM T1 
UNION 
SELECT * FROM T2

你可能感兴趣的:(MySQL,数据库,mysql)