自学sql难题解决方案

点点圈 提交于 2019-12-21 05:44:05

这个网站有助于复习sql知识,网址:http://xuesql.cn/lesson/select_queries_with_aggregates_pt_2

在这里插入图片描述

重点解决最后两道题

1.1 角色分组算出每个角色按有办公室和没办公室的统计人数(列出角色,数量,有无办公室,注意一个角色如果部分有办公室,部分没有需分开统计)

  • 考虑用联合查询解决,分别查询有无办公室人数再联合
SELECT role,count(building),"yes" FROM employees a group by role 
union 
select role,count(name),"no" from employees b where building is null group by role

1.2 按角色和就职年份统计人数,年份按0-3,3-6,6-9这种阶梯分组,最后按角色+阶梯分组排序

  • 还是用联合查询
select Role,count(name),"0-2" from employees where Years_employed between 0 and 2 group by Role 
union 
select Role,count(name),"3-5" from employees where Years_employed between 3 and 5 group by Role
union
select Role,count(name),"6-9" from employees where Years_employed between 6 and 9 group by Role

2.查找最晚入职员工的所有信息——来自牛客网mysql在线练习第一题

CREATE TABLE `employees` (
`emp_no` int(11) NOT NULL,
`birth_date` date NOT NULL,
`first_name` varchar(14) NOT NULL,
`last_name` varchar(16) NOT NULL,
`gender` char(1) NOT NULL,
`hire_date` date NOT NULL,
PRIMARY KEY (`emp_no`));

答案:

1select * from employees where hire_date=(select max(hire_date) from employees);2select * from employees order by hire_date desc limit 1
  • 解析:这一题如果只要求显示一条记录用第2种方法没有问题,但是可能会存在多个员工同一天入职的情况,因此用第1种方法更合理,他可以查出最晚一天同事入职的多名员工信息。
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!