今天突然一个朋友给我突然给我发了一份建立,他选择还是在职状态,但是没事的时候他就喜欢投投简历,来更了解现在的工资行情,他是一个智能AI运维工程师,周日的时候呢,他接到了一家小企业的面试要求,还是线下,到了之后人事简单问了一些工作方面的问题,然后就给他丢过来了一张关于SQL的题,但是这个题我第一眼一看好简单啊,可以在我做的时候确不如此,废话少说,我们来帮他做一下吧。
查询SQL的方法有很多,大家可以来做一下,如果有更高效的方法欢迎大家评论,如果发现哪里我有写的不对的地方也欢迎大家来纠正
创建原表:
create table user(id int primary key,name varchar(10),age int,sex char(1)); create table salary(userid int, salary int, month int, year int); alter table salary add foreign key(userid) references user(id); insert into user values(1,'zhangsan',27,'n'),(2,'lisi',28,'n'),(3,'wuwang',29,'v'); insert into salary values(1,1000,1,2004),(1,1000,2,2004),(1,2000,3,2004),(2,2000,1,2004),(2,2000,2,2004),(2,2000,3,2004),(3,2000,1,2004),(3,2000,2,2004),(3,2000,3,2004);
1,求2004年一月份工资最低的员工姓名
mysql> select * from user u join salary s on u.id=s.userid and salary = (select min(salary) from salary where year=2004 and month=1) and year=2004 and month=1; +----+----------+------+------+--------+--------+-------+------+ | id | name | age | sex | userid | salary | month | year | +----+----------+------+------+--------+--------+-------+------+ | 1 | zhangsan | 27 | n | 1 | 1000 | 1 | 2004 | +----+----------+------+------+--------+--------+-------+------+ 1 row in set (0.00 sec)
2,删除User表中Sex为女的用户,在 Salary 表中的所有信息
delete from salary where userid=(select id from user where sex='v');
3,求Sex 等于男的用户,2004 年第一季度的平均工资
mysql> select u.sex,avg(s.salary) from user u inner join salary s on u.id=s.userid and sex='n' and year=2004 and month between 1 and 3 group by u.sex; +------+---------------+ | sex | avg(s.salary) | +------+---------------+ | n | 1666.6667 | +------+---------------+ 1 row in set (0.00 sec)
4,求Sex 等于男并且2004年3 月份有涨工资的用户
mysql> select a.name from (select u.name,s.salary from salary s join user u on u.id=s.userid and u.sex ='n' and month=2) a,(select u.name,s.salary from salary s join user u on u.id=s.userid and u.sex='n' a nd month=3) b where a.name=b.name and b.salary>a.salary; +----------+ | name | +----------+ | zhangsan | +----------+ 1 row in set (0.00 sec)